Key capture for a form, but not for controls

I have a simple modal form that I would like to close when the button is pressed Esc. This is a simple implementation of this event form_KeyDown. The problem is form control. When the form first starts, one of the buttons gets focus and pressing Esc, of course, does nothing. Disabling TabStopeach button prevents this, but Escstops working again when any button is used. Is there a way to do this and then handle KeyDowneach control on the form?

+3
source share
3 answers

You need to set the property KeyPreviewon the form trueand handle the form event previewkeydown.

+4
source

Does your form have a Cancel button?

If so set the CancelButtonform property for this button.

This closes the form when clicked Esc.

+8
source

- Compact Framework ( F1..Fn , ). Simon P Stevens .NET, PreviewKeyDown CF. , :

  • KeyDown For Each ctl As Control In Controls AddHandler ctl.KeyDown, AddressOf OnControlKeyDown

  • Create OnControlKeyDownand perform special processing for the Fn keys. All other keystrokes remain as they are.

This is apparently a fairly simple way to implement this for the Compact Framework.

0
source

Source: https://habr.com/ru/post/1711078/


All Articles