简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM