ProcessCmdKey firing twice, WinForms

放肆的年华 提交于 2019-12-11 23:02:07

问题


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);
        }

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

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.


回答1:


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

The ProcessCmdKey method first determines whether the control has a ContextMenu, and if so, enables the ContextMenu to process the command key. If the command key is not a menu shortcut and the control has a parent, the key is passed to the parent's ProcessCmdKey method. The net effect is that command keys are "bubbled" up the control hierarchy. In addition to the key the user pressed, the key data also indicates which, if any, modifier keys were pressed at the same time as the key. Modifier keys include the SHIFT, CTRL, and ALT keys.

per 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.



来源:https://stackoverflow.com/questions/32617960/processcmdkey-firing-twice-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!