我有一个 C# winform,上面有 1 个按钮。
现在,当我运行我的应用程序时,按钮会自动获得焦点。
问题是我的表单的 KeyPress
事件不起作用,因为按钮已获得焦点。
我已经在 FormLoad()
事件上尝试了 this.Focus();
,但 KeyPress 事件仍然无法正常工作。
最佳答案
您需要覆盖 ProcessCmdKey
method为你的表格。这是当子控件具有键盘焦点时发生的键事件通知您的唯一方式。
示例代码:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// look for the expected key
if (keyData == Keys.A)
{
// take some action
MessageBox.Show("The A key was pressed");
// eat the message to prevent it from being passed on
return true;
// (alternatively, return FALSE to allow the key event to be passed on)
}
// call the base class to handle other key events
return base.ProcessCmdKey(ref msg, keyData);
}
至于为什么this.Focus()
不起作用,是因为表单本身不能获得焦点。一个特定的 control 必须有焦点,所以当你将焦点设置到表单时,它实际上将焦点设置到第一个可以接受具有最低 TabIndex
的焦点的控件> 值(value)。在这种情况下,这是您的按钮。
关于c# - 触发表单按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44618106/