Close Application at Press of Escape Button

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)
    this.Close();
  • 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)
        this.Close();
}
so after taking these all steps, you will able to close application at press of escape button.
Article Posted in CP
I’ve also posted this article as a Tips/Tricks in CodeProject.
Take a look There
Advertisements

About Ravi Ranjan Kumar

An Indian who Living, Loving & Learning Technology with different tastes and willing to share knowledge and thoughts.
This entry was posted in .Net, C#, Tips&Tricks and tagged , , . Bookmark the permalink.

2 Responses to Close Application at Press of Escape Button

  1. nancy says:

    I was looking for it. very helpful

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s