The Solutin 1 by
Prasad_Kulkarni and Solution 2 by
Rahul Rajat Singh are good.
I want to add that when a key is pressed it will go to the
control
which has
focus
on the form. Let us say the cursor is in a
TextBox
. Now, if the
Escape key
is pressed it will not go to the
Form's KeyUp
event and instead it is captured by the
TextBox
and the
KeyUp
event of
TextBox
fires.
So, to enable the
KeyUp
event of
Form
even when the focus is on any other control, then the
KeyPreview
property of the
Form
has to be set to
true
as explained here
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx[
^]
Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.
and under remarks as
To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.
After setting
KeyPreview
property the
Form's KeyUp
event will fire first, then the
KeyUp
event of the control which has focus will be fired.