gpt4 book ai didi

c# - 阻止 Winform 击键到达子控件

转载 作者:太空狗 更新时间:2023-10-30 01:18:59 24 4
gpt4 key购买 nike

我有一个包含多个按钮的表单。我将 KeyPreview 设置为 true,并且我有 KeydownKeyPress 和 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com