在 KeyPress 事件中获取 KeyCode 值

Get KeyCode value in the KeyPress event

如何修复此错误:

'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?)

代码:

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

我正在为这个项目使用 Visual studio 2010 框架 4。

您无法从 KeyPress(至少不使用某些映射)事件中获取 KeyCode,因为 KeyPressEventArgs provide only the KeyChar 属性.

但是您可以从 KeyDown event 中获取它。 System.Windows.Forms.KeyEventArgs 具有所需的 KeyCode 属性:

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

如果 KeyDown 事件不适合您,您仍然可以将 KeyCode 保存在某个私有字段中,稍后在 KeyPress 事件中使用它,因为在正常情况下,每个 KeyPress 之前都会有 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 ");
     }
}

试试这个

    private void game_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Enter)
            MessageBox.Show(Keys.Enter.ToString(), "information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }