[英]Override KeyDown from another class C#
I have a form that creates a class. 我有一个创建类的表格。 This class processes events that are fired on the form. 此类处理在表单上触发的事件。 The problem is I am trying to use the KeyDown event, but it isn't working because there are buttons on the form and they are capturing the KeyDown. 问题是我正在尝试使用KeyDown事件,但是它不起作用,因为表单上有按钮并且它们正在捕获KeyDown。 I found the solution on another post was to override the ProcessCmdKey. 我发现另一篇文章的解决方案是覆盖ProcessCmdKey。 The problem is I don't know how to override a method from inside another class. 问题是我不知道如何从另一个类内部重写一个方法。 Can anyone tell me how I can capture all KeyDown events from inside my other class? 谁能告诉我如何从另一个类中捕获所有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);
}
The easiest way to do this would be to expose the KeyDown
from Button
on the containing form. 最简单的方法是在包含窗体上的Button
暴露KeyDown
。
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);
}
};
}
}
Now the calling code can simple hook into the MyForm::ButtonKeyDown
event 现在,调用代码可以简单地挂接到MyForm::ButtonKeyDown
事件中
I'm not sure how you're wiring up the events with your class, but if you set the KeyPreview property of the form to True, you can grab a hold of the event there and then pass it along to your class that is processing the events. 我不确定如何将事件与您的类联系起来,但是如果您将表单的KeyPreview属性设置为True,则可以在那里保留事件,然后将其传递给正在处理的类事件。 So even when the button has the focus, the KeyDown will fire the event on the form. 因此,即使按钮具有焦点,KeyDown也会在窗体上触发事件。
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
... Invoke your class
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.