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

前端 未结 2 1824
渐次进展
渐次进展 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: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.

提交回复
热议问题