Get KeyCode value in the KeyPress event

只愿长相守 提交于 2019-12-04 06:34:43

问题


How to fix this error:

'System.Windows.Forms.KeyPressEventArgs' does not contain a definition for 'KeyCode' and no extension method 'KeyCode' accepting a first argument of type 'System.Windows.Forms.KeyPressEventArgs' could be found (are you missing a using directive or an assembly reference?)

Code:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (e.KeyCode == Keys.Enter)
     {
         MessageBox.Show("Enter Key Pressed ");
     }
}

I'm using Visual studio 2010, framework 4 for this project.


回答1:


You can't get KeyCode from KeyPress(at least without using some mapping) event because KeyPressEventArgs provide only the KeyChar property.

But you can get it from the KeyDown event. System.Windows.Forms.KeyEventArgs has the required KeyCode property:

    private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
       MessageBox.Show(e.KeyCode.ToString());
    }

If the KeyDown event doesn't suit you, you can still save the KeyCode in some private field and use it later in the KeyPress event, because under normal circumstances each KeyPress is preceeded by KeyDown:

Key events occur in the following order:

  • KeyDown

  • KeyPress

  • KeyUp

private Keys m_keyCode;

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    this.m_keyCode = e.KeyCode;
}

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (this.m_keyCode == Keys.Enter)
     {
         MessageBox.Show("Enter Key Pressed ");
     }
}


来源:https://stackoverflow.com/questions/29576525/get-keycode-value-in-the-keypress-event

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