Victor Parmar
Victor Parmar

Reputation: 5789

Autocomplete on Combobox onkeypress event eats up the Enter key

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)

Upvotes: 4

Views: 14249

Answers (1)

Shuhel Ahmed
Shuhel Ahmed

Reputation: 963

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

Upvotes: 6

Related Questions