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

标签 c# winforms

我有一个包含多个按钮的表单。我将 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/

相关文章:

c# - 防止 ListView 丢失所选项目

c# - 方法 'xxx' 不能是事件的方法,因为此类的派生类已经定义了该方法

c# - Windows 窗体触地事件

.net - 设置Datasource后DataGridView为空

c# - 在负十六进制和负十进制之间转换会给出错误的结果

c# - 在子对话框中获取 LUIS 实体

c# - 将 base64 字符串写入不带回车符的文件

c# - 无法将 lambda 表达式转换为类型 'ServiceLifetime',因为它不是 Asp.net core 2.2 上的委托(delegate)类型

c# - 作为 session 从 gridview 传递数据

c# - 如何使用 wcf 服务获取 facebook 授权码