How to prevent controls from capturing KeyDown events while a modal form is open?

前端 未结 2 1822
渐次进展
渐次进展 2021-01-22 11:51

I have a form with CancelButton and AcceptButton (named btnCancel and btnOK). And I have some ComboBoxes as input fields.

ComboBoxes prevent my AcceptButton and CancelBu

相关标签:
2条回答
  • 2021-01-22 12:05

    While I have no idea about the main reason behind this behavior.

    But in this situation obviously KeyDown event triggers 2 times. (Set a breakpoint and you will see.)

    Since you need to handle it in code, You can try this to neglect one of Enter keys:

    bool handled = true;
    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            /*Prevent handling the Enter key twice*/
            handled = !handled;
            if(handled)
                return;
    
            //Rest of logic
            //OkButton.PerformClick();
        }
    }
    
    0 讨论(0)
  • 2021-01-22 12:24

    You cannot correctly process Escape and Enter key in KeyDown event because they are handled during the keyboard preprocessing phase - Control.IsInputKey and Control.ProcessDialogKey. Normally controls do that for you, but looks like there is a bug in ComboBox implementation when DropDownStyle is Simple.

    To get the desired behavior, create and use your own ComboBox subclass like this

    public class MyComboBox : ComboBox
    {
        protected override bool IsInputKey(Keys keyData)
        {
            if (DropDownStyle == ComboBoxStyle.Simple)
            {
                switch (keyData & (Keys.KeyCode | Keys.Alt))
                {
                    case Keys.Return:
                    case Keys.Escape:
                        return false;
                }
            }
            return base.IsInputKey(keyData);
        }
    }
    

    P.S. And of course don't forget to remove your KeyDown event handlers.

    0 讨论(0)
提交回复
热议问题