Autocomplete on Combobox onkeypress event eats up the Enter key

13,650

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! :-)

Share:
13,650
Victor Parmar
Author by

Victor Parmar

Updated on June 04, 2022

Comments

  • Victor Parmar
    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
    Victor Parmar over 13 years
    That was it! Thanks a bunch :)
  • mistertodd
    mistertodd over 12 years
    This solution also works for Delphi and the OnKeyPress vs OnKeyDown events.