views:

212

answers:

4

I have a simple modal form which I'd like to close when Esc key pressed. It's simple doing this handling form_KeyDown event. The problem is the controls on the form. When the form first launched one of the buttons get focus and pressing Esc of course doesn't do anything. Disabling TabStop of every button prevents this but again Esc stops working when any button is used. Is there a way to do this other then handling KeyDown of every control on the form?

+7  A: 

Does your form have a Cancel button?

If so set the CancelButton property of the form to that button.

This will close the form when Esc is pressed.

ChrisF
+1 this is the easiest.
Adam Neal
A: 

It might be overkill, but have you looked at jQuery?

JQuery is a JavaScript library for web applications, the question is tagged "winforms" so we are talking regular windows application here; jQuery is not applicable.
Fredrik Mörk
I should have benn more clear sorry about that.
Armagan
+2  A: 

You need to set the KeyPreview property on the form to true, and handle the forms previewkeydown event.

Simon P Stevens
This was it, thanks.
Armagan
A: 

I was trying to do more-or-less the same thing in a Compact Framework application (I wanted to have the Form capture F1..Fn keys and handle them in a global manner, while letting controls handle cursor & numeric keys). Simon P Stevens' solution above is ideal for desktop .NET but PreviewKeyDown isn't supported by the CF. So my solution was:

  • when loading a form, register each control's KeyDown handler using For Each ctl As Control In Controls and AddHandler ctl.KeyDown, AddressOf OnControlKeyDown

  • Create OnControlKeyDown and do special processing for the Fn keys there. All other key strokes are left as-is.

This seems to be a reasonably easy way to implement this for the Compact Framework.

AAT