Sunday, July 4, 2010

Forwarding Key Inputs to the Form / Key Preview

Suppose, you want to define different key combinations globally on the form. For example, that the program should exit when pressing ESC or that a search function is called when pressing "CTRL + F".
On the form though will probably be controls like textboxes etc. which "take the focus away" from it.
If the user presses "ESC" then and a control has the focus, the key event of that control and not that of the form is triggered.
One possibility would be, to manually forward key events in one function.
Luckily there is a much more comfortable way though, we just have to set the property KeyPreview of the form to true.
Now all key presses are reported to the form as well.
Note though, that this just holds for key events which happen when the application is active, meaning key events which occur when another application has the focus are not treated.
Doing that is much harder, as there a so called KeyHooks is needed, about which I will post some other time.

No comments:

Post a Comment