Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting an item from AutoComplete suggestion list raises KeyDown-event with ENTER key

In Winforms I have a textbox with AutoCompleteMode set to SuggestAppend and a AutoCompleteCustomSource set. When the user types some letters the suggestion list is shown. If an item of this list is selected by clicking it with the mouse, the KeyDown-event of the form containing the textbox is raised for the ENTER key.

Is there any possibility to NOT raise this event when selecting a suggested item with the mouse?

like image 776
user1225775 Avatar asked Aug 21 '12 13:08

user1225775


2 Answers

The AutoComplete feature has a couple of quirks that were inherited from its original designed use, the address box of Internet Explorer. This includes emitting the Enter key when you click on an item in the list. Pressing Enter in the address box of IE makes it navigate to the entered URL.

There isn't anything you can do about that, the native interface (IAutoComplete2) has very few options to configure the way it works. It pokes the keystrokes into the text box by faking Windows messages. Which is one way you can tell the difference, the actual key won't be down. Something you can check by pinvoking GetKeyState(), like this:

    private void textBox1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyData == Keys.Enter && GetKeyState(Keys.Enter) < 0) {
            Console.WriteLine("Really down");
        }
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern short GetKeyState(Keys key);
like image 81
Hans Passant Avatar answered Oct 20 '22 03:10

Hans Passant


You can catch keydown keys:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
    //Do nothing or something
    }
}
like image 32
TrizZz Avatar answered Oct 20 '22 01:10

TrizZz