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