views:

245

answers:

1

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?

+3  A: 

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.

whatknott
Will setting e.Handled to true discard the keypress?
tinmaru
Yes. Basically, you are telling the event that you handled the key event and you don't want it to do anything with it.
whatknott
In fact I used KeyDown which handle the both following case:- When typing character the list item are not selected.- When hitting the Up/Down arrow the list item selection does'nt changePlease edit your answer so I mark it as accepted.
tinmaru
Hmmm. What version of the framework/visual studio are you using? Handling KeyDown only works for the up/down arrows for me. I have to handle the KeyPress if I don't want letters to select listbox items. Are you using the out-of-the-box listbox control?
whatknott