Martin Delille
Martin Delille

Reputation: 11810

Winform keyboard management

I would like to control the focus of my winform application. It is made of a custom listbox and several other component. I want all the keyboard event be managed by my window handlers in order to avoid specific control key handling (for example when I press a character and the list box is focused, the item starting with the correspondant letter is selected which is not a correct behaviour for my application). How can I achieve this?

Upvotes: 2

Views: 998

Answers (1)

codeConcussion
codeConcussion

Reputation: 12938

Make sure your form's KeyPreview property is set to true. Then this code should work for canceling your key events to the listbox...

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (this.ActiveControl == listBox1)
        e.Handled = true;
}

The KeyPress event may not work for all your scenarios. In that case, I would try out the KeyDown event.

Upvotes: 4

Related Questions