Click here to Skip to main content
15,891,607 members
Articles / Programming Languages / C#
Tip/Trick

Close Application at Press of Escape Button

Rate me:
Please Sign up or sign in to vote.
4.88/5 (18 votes)
10 Nov 2011CPOL 72.5K   15   17
How to close Form at pressing 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:
  • C#
    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:
  • C#
    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:
  • C#
    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
            this.Close();
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 4 Good options Pin
All Time Programming4-Jul-11 20:12
All Time Programming4-Jul-11 20:12 
GeneralRe: Thanks :) Pin
RaviRanjanKr4-Jul-11 20:38
professionalRaviRanjanKr4-Jul-11 20:38 
GeneralReason for my vote of 5 nice Pin
Pritesh Aryan1-Jul-11 23:35
Pritesh Aryan1-Jul-11 23:35 
GeneralRe: Thanks Pritesh. Pin
RaviRanjanKr2-Jul-11 0:12
professionalRaviRanjanKr2-Jul-11 0:12 
SuggestionYou don't need all this... Pin
Indivara29-Jun-11 15:29
professionalIndivara29-Jun-11 15:29 
GeneralRe: You don't need all this... Pin
RaviRanjanKr30-Jun-11 2:18
professionalRaviRanjanKr30-Jun-11 2:18 
GeneralRe: You don't need all this... Pin
Indivara1-Jul-11 1:01
professionalIndivara1-Jul-11 1:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.