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

£可爱£侵袭症+ 提交于 2019-12-05 11:49:29
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;
            //...
    }
}
     private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.D1) // number 1
        {
            MessageBox.Show("Hello");
        }
    }

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