Autocomplete on Combobox onkeypress event eats up the Enter key
Difference between KeyDown and KeyPress
In your case the best you may do is use KeyDown event.
void SearchBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
// Do stuff
}
}
Another interesting thing about KeyPress event is: it even catches Enter key with autocompete on if the combobox has no items! :-)
Victor Parmar
Updated on June 04, 2022Comments
-
Victor Parmar almost 2 years
I have a ComboBox with
AutoCompleteMode = suggest
and handle the KeyPress event like so:private void searchBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Return) { // do stuff } }
However, it does not catch the
Enter
key. It catches everything else since the autocomplete dropdown works perfectly.I also tried the suggestion offered here : http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/2db0b540-756a-4a4f-9371-adbb92409806, set the form's
KeyPreview
property to true and put a breakpoint in the form's KeyPress event handler:private void Form_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = false; }
However, even the form's handler was not catching the enter key!
Any suggestions?
(If I disable the autocomplete, it catches the Enter key)
-
Victor Parmar over 13 yearsThat was it! Thanks a bunch :)
-
mistertodd over 12 yearsThis solution also works for Delphi and the
OnKeyPress
vsOnKeyDown
events.