我有一个包含多个按钮的表单。我将 KeyPreview 设置为 true,并且我有 Keydown
、KeyPress
和 keyup 事件都在读取
form_keyevent(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
e.handled = true;
}
出于某种原因,回车键仍然单击具有焦点的按钮。我错过了什么?有解决办法吗?
最佳答案
在带有焦点按钮的 Form
上按 Enter 键会调用 Form.ProcessCmdKey
method :
This method is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. Examples of command keys include accelerators and menu shortcuts.
您可以覆盖此方法以将 key 标记为已处理:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// if enter pressed, return 'true' to skip default handler
if ((keyData & Keys.Return) == Keys.Return)
return true;
return base.ProcessCmdKey(ref msg, keyData);
}
如果你只想在按钮获得焦点时忽略 Enter,你可以使用类似的东西:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// if a button is focused AND enter pressed, skip default handler
if (this.ActiveControl is Button && (keyData & Keys.Return) == Keys.Return)
return true;
return base.ProcessCmdKey(ref msg, keyData);
}
关于c# - 阻止 Winform 击键到达子控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24910807/