本文介绍了ProcessCmdKey 触发两次,WinForms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我的 ProcessCmdKey 在我按下按钮时会触发两次.这是我的代码:

I'm wondering why my ProcessCmdKey fires twice, when i press the button. Here's my code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                if (this.tsComboBoxFontChoice.Focused)
                {
                    this.tsComboBoxFontChoice.Text = this.startFontComboBoxText;
                    this.richTextBox.Focus();
                    this.tsComboBoxFontChoice.Focus();
                    this.isEscClicked = true;
                    return true;
                }
                else if (this.tsComboBoxFontSizeChoice.Focused)
                {
                    this.tsComboBoxFontSizeChoice.Text = this.startFontSizeComboBoxText;
                    this.tsComboBoxFontSizeChoice.Focus();
                    return true;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

我还为我的表单定义了 KeyDown 事件,这可能是原因吗?

I have also defined KeyDown event for my form, might it be the reason?

还有一点:如果我想为 RichTextBox 定义 KeyDown/KeyUp/KeyPressed 事件,它会不会与 ProcessCmdKey 发生冲突?我从来没有覆盖默认方法,但这次我被迫.

And one more: if I would like to define KeyDown/KeyUp/KeyPressed event for the RichTextBox, won't it collide with ProcessCmdKey? I've never overriden default methods, but this time I am forced to.

推荐答案

我相信您的 ProcessCmdKey 多次触发的原因是:

I believe the reason your ProcessCmdKey is firing multiple times is this:

ProcessCmdKey 方法首先判断控件是否有 ContextMenu,如果有,则启用 ContextMenu 处理命令键.如果命令键不是菜单快捷方式并且控件有父项,则该键将传递给父项的 ProcessCmdKey 方法.最终效果是命令键在控件层次结构中冒泡".除了用户按下的键之外,键数据还指示与该键同时按下的修饰键(如果有).修饰键包括 SHIFT、CTRL 和 ALT 键.

每个 MSDN:https://msdn.microsoft.com/en-us/library/system.windows.forms.control.processcmdkey(v=vs.110).aspx

在你的方法中,我看到你正在检查哪个控件是焦点.所以这个方法是为那个控件触发的,然后是父控件(我假设是表单),因为聚焦控件不太可能有快捷键或其他什么.

In your method there, I see you're checking which control is focused. So this method is firing for that control, then for the parent control (which I assume is the form) because it's unlikely that focused control has has a shortcut key or whatever.

这篇关于ProcessCmdKey 触发两次,WinForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 02:34