Close Application at Press of Escape Button

Posted by RaviRanjanKr under Windows Forms category on | Points: 40 | Views : 3794
There are various ways to close an application by pressing the Escape button, using C#. Here are a few:

Way 1: Simply add the below given code in your Windows program:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
if (keyData == Keys.Escape) this.Close();
bool res = base.ProcessCmdKey(ref msg, keyData);
return res;

Way 2: Write the below code in the KeyPress event of a form:

if (e.KeyChar == (char)27)

Way 3: Select properties of Form and select 'KeyPreview' and change it from 'false' to 'true'. [By default, its value is false.] Then write the below code in the KeyUp event of the Form:

private void Form1_KeyUp(object sender, KeyEventArgs e)
if (e.KeyCode == Keys.Escape)

Comments or Responses

Posted by: Certifiedkiller2000 on: 7/26/2011 Level:Starter | Status: [Member] | Points: 10
nice ...

i would also like to add the cancel button property

this.CancelButton = this.button2; (in formnamedesigner.cs file) or select it in the form property after adding a button

and then

private void button2_Click(object sender, EventArgs e)

Posted by: RaviRanjanKr on: 7/28/2011 Level:Starter | Status: [Member] | Points: 10
yeah! You can also do this code to close application at press of escape button but for this you need to work with an additional Control. like you are using button here.
I don't want to suggest such type of way to use any other controls for close Application at press of Escape button.
By the way Thanks for share you effort here. :)

Login to post response