C# – Basic WinForm KeyDown event handling

cevent handlingkeydownwinforms

I'm using WinForms. I've created an event handler for the KeyDown event of the main form, thereby invoking a button's Click event handler.

The Click event handler called is dependent upon the specific key pressed. If a user clicks the button rather than using the key, and then subsequently tries to use the key thereafter, the key (down arrow for example) acts as a tab-cycle, changing focus between each button control on the form (rather than executing the Keydown handler).

Any ideas ?

Best Answer

The problem is, the button has the focus when it is clicked, so subsequent key presses are not caught by the form itself, but by the buttons instead. In the click event handler for the buttons, focus the form:

this.Focus();

That way, focus is restored to the form so the form will listen for the keypress events.

Edit

The real problem, as you have discovered, is that arrow keys are not treated as input keys. To fix this, you need to create a new class that inherits whatever control you want to use. Then, you override the IsInputKey method to treat arrow keys as input keys. Check this link: http://bytes.com/topic/c-sharp/answers/517530-trapping-arrow-keys-usercontrol. This article is also useful: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isinputkey.aspx.

Related Topic