【问题标题】:Get KeyCode value in the KeyPress event在 KeyPress 事件中获取 KeyCode 值
【发布时间】:2015-06-17 01:31:25
【问题描述】:

如何解决这个错误:

'System.Windows.Forms.KeyPressEventArgs' 不包含定义 对于 'KeyCode' 并且没有扩展方法 'KeyCode' 接受第一个 'System.Windows.Forms.KeyPressEventArgs' 类型的参数可以是 找到(您是否缺少 using 指令或程序集引用?)

代码:

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

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

【问题讨论】:

标签: c# winforms keypress


【解决方案1】:

您无法从KeyPress(至少不使用某些映射)事件中获取KeyCode,因为KeyPressEventArgs 仅提供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 之前:

关键事件按以下顺序发生:

  • 按键

  • 按键

  • 按键

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 ");
     }
}

【讨论】:

  • 另一个错误:No overload for 'Form1_KeyPress' matches delegate 'System.Windows.Forms.KeyPressEventHandler'
  • @Smygolas 您必须删除旧的处理程序Form1_KeyPress(手动或从编辑器的表单属性中),然后为Form1_KeyDown 添加一个新的处理程序
  • 另一个错误:The type or namespace name 'KeyCode' could not be found (are you missing a using directive or an assembly reference?)
  • @Smygolas 抱歉,实际上是Keys 。在您的场景中,您也许只能使用没有私有字段的 KeyDown 事件。
  • 它不起作用,我按回车但消息框不显示
【解决方案2】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多