我有一个包含许多控件的父表单。 我尝试过滤该表单的所有按键操作。 问题是,如果焦点在表单上的某个控件上,则父表单不会收到按键事件,那么该如何捕获按键按下事件?
在你的窗体上设置KeyPreview为true,你就能捕获它们:MSDN
这只适用于表单,如果其他组件处于焦点状态,则不起作用。
public partial class ChildForm : Form
{
public ChildForm()
{
KeyPress += KeyPressHandler;
}
public KeyPressHandler(object sender, KeyPressEventArgs e)
{
if (_parent != null)
{
_parent.NotifyKeyPress(e);
}
}
}
即使其他组件处于焦点状态,这也可以正常工作。
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.F1)
{
MessageBox.Show("You pressed the F1 key");
return true; // indicate that you handled this keystroke
}
// Call the base class
return base.ProcessCmdKey(ref msg, keyData);
}