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

前端 未结 2 1825
渐次进展
渐次进展 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();
        }
    }
    

提交回复
热议问题