Do you wish to allow your users to exit your application, or close a windows form when they press the Escape key?
Well first of all, it may be really easy for you if you have a custom “Cancel” button already featured on the screen, as you can simply hook that additionally by the Escape key. If this is the case, just simply bind your Cancel button in the CancelButton property featured on your form control and away you go!
However, if you do not have a Cancel button, like me, perhaps for an initial Login screen or some such, you may just wish to bind the Escape key to Close/Quit your application nonetheless..
Well, if you have tried either:
private void FormLogin_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
this.Close();
}
or this:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)27)
this.Hide();
}
and found to no avail that the form doesn’t close, it is most likely due to the fact you currently do not have the window itself in focus, which is hard and annoying to do, plus not desirable for your users. You will most likely want your form to close all the time, no matter what control is selected when you press the Escape key right?
Well this approach works a treat, will handle the raw key command and you just need to plug it in to your win form code behind:
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
try
{
if (msg.WParam.ToInt32() == (int)Keys.Escape)
{
this.Close();
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}
catch (Exception Ex)
{
MessageBox.Show("Key Overrided Events Error:" + Ex.Message);
}
return base.ProcessCmdKey(ref msg, keyData);
}
5 Comments
Nice post. Also see:
How to trap keystrokes in controls by using Visual C#
http://support.microsoft.com/kb/320584
It’s so easy.
Form1.KeyPreview =true;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode==Keys.Escape )
{
this.Close();
}
}
You mean like in my first example?
It doesn’t always work.
Great solution, thank you!
Post a Comment