KeyEventArgs in C#

一笑奈何 提交于 2019-12-11 18:09:51

问题


I have a problem to how to catch which key is pressed. This is my code, but i cant get what key was pressed. I'm using KeyEventArgs for declaration of new variable and then comparing it.

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        KeyEventArgs k = null;
        if (e is KeyEventArgs)
        {
            k = (KeyEventArgs)e;
        }

        if (k.KeyCode == Keys.Enter)
        {
            // do something here
        }


    }

回答1:


You need to add:

 [component_name].KeyDown += new System.Windows.Forms.KeyEventHandler(this.Key_Pressed_Method);

into the constructor of your Form. Then, you can define what you want to do in Key_Pressed_Method() method.




回答2:


TextChanged won't give you a KeyEventArgs. You want KeyUp, KeyDown or KeyPress instead. KeyPress gives you KeyPressEventArgs instead.



来源:https://stackoverflow.com/questions/15746499/keyeventargs-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!