How do I catch KeyUp event ? (sample of code, please)

喜夏-厌秋 提交于 2019-12-07 10:47:08

问题


I need to catch KeyDown & especially KeyUp events for 1,2,3,4,5,6,7,8,9 keyboard buttons.

How does it do ?
I can catch KeyDown event but what about KeyUp ?
Please, provide some simple code.


回答1:


private void Form1_Load(object sender, EventArgs e)
{
    this.KeyUp += new KeyEventHandler(Form1_KeyUp);
}

void Form1_KeyUp(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.NumPad1:
            break;
        case Keys.NumPad2:
            break;
            //...
    }
}



回答2:


     private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.D1) // number 1
        {
            MessageBox.Show("Hello");
        }
    }



回答3:


If you need the logic to be exactly the same then you can hook up the same event handler to both the KeyUp and KeyDown events of the control you want to capture input on.

// this occurs as part of Initialisation via the designer or you can hook up manually
myControl.KeyDown += myControl_KeyChange;
myControl.KeyUp += myControl_KeyChange;
// ...

private void myControl_KeyChange(object sender, KeyEventArgs e)
{
    switch( e.KeyCode )
    {
        case Keys.1:
        {
            // handle the 1 key being pressed
            break;
        }        
        case Keys.2:
        {
            // handle the 2 key being pressed
            break;
        }
        // etc
    }
}


来源:https://stackoverflow.com/questions/3674810/how-do-i-catch-keyup-event-sample-of-code-please

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