【问题标题】:Keydown Event not firingKeydown 事件未触发
【发布时间】:2014-09-30 20:37:41
【问题描述】:

当按下键盘上的按钮时尝试触发事件。我已将 Form1 属性设置为也将 KeyPreview 设置为 True。但是,它仍然没有触发,我看不出有什么问题。

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Modifiers == Keys.A)
    MessageBox.Show("A pressed");
    else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.F1)
    MessageBox.Show("Combination of ALt and F1 pressed");
}

【问题讨论】:

  • 显示处理程序无济于事,您需要显示附加事件的位置。
  • 我讨厌看到没有大括号的if 语句。
  • 为什么是e.Modifiers?为什么不e.KeyCode
  • 重复:[stackoverflow.com/questions/3172731/… 如果问题仍然存在,请发布更多详细信息。

标签: c# .net windows winforms


【解决方案1】:

设置事件

this.KeyDown += Form5_KeyDown;
this.KeyPreview = true;

事件

void Form5_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
        MessageBox.Show("A pressed");
    else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.F1)
        MessageBox.Show("Combination of ALt and F1 pressed");
}

不要忘记KeyPreview = true,如果你想处理所有keydown

【讨论】:

    【解决方案2】:

    尝试使用 KeyCode:

    if (e.KeyCode==Keys.A)
                    MessageBox.Show("A pressed");
                ...
    

    还要记住Form1在按下相应按钮时必须有焦点

    【讨论】:

    • 试过了,还是没有触发。此外,KeyPreview 属性在正确的表单上设置为 true。
    【解决方案3】:

    将表单的 KeyPreview 属性设置为 true。

    否则子控件会先捕获事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多