0

我有一个创建类的表单。此类处理在表单上触发的事件。问题是我正在尝试使用 KeyDown 事件,但它不起作用,因为表单上有按钮并且它们正在捕获 KeyDown。我在另一篇文章中发现解决方案是覆盖 ProcessCmdKey。问题是我不知道如何从另一个类中覆盖一个方法。谁能告诉我如何从其他班级中捕获所有 KeyDown 事件?

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Left)
    {
        MoveLeft(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else if (keyData == Keys.Right)
    {
        MoveRight(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else if (keyData == Keys.Up)
    {
        MoveUp(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else if (keyData == Keys.Down)
    {
        MoveDown(); DrawGame(); DoWhatever();
        return true; //for the active control to see the keypress, return false
    }
    else
        return base.ProcessCmdKey(ref msg, keyData);
}
4

2 回答 2

0

最简单的方法是在包含表单上公开KeyDownfrom 。Button

class MyForm : Form { 
  Button m_button;

  public event KeyEventHandler ButtonKeyDown;

  public MyForm() { 
    m_button = ...;
    m_button.KeyDown += delegate (object, e) {
      KeyEventHandler saved = ButtonKeyDown;
      if (saved != null) { 
         saved(object, e);
      }
    };
  }
}

现在调用代码可以简单地挂钩MyForm::ButtonKeyDown事件

于 2013-07-24T21:42:16.777 回答
0

我不确定你是如何将事件与你的类联系起来的,但是如果你将表单的 KeyPreview 属性设置为 True,你可以在那里抓住事件,然后将它传递给你正在处理的类事件。因此,即使按钮具有焦点,KeyDown 也会在表单上触发事件。

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    ... Invoke your class
}
于 2013-07-24T22:09:22.097 回答