Closing a Windows Form by pressing ESC key

Closing a Windows Form by pressing ESC key

  • Comments 6

While I was developing one Windows Forms application, it was required for me to close the popup forms when user will press ESC key. I tried adding the Form’s KeyPress event. It was not working as expected. Then I thought I should write a code to find all the controls to my form and add the KeyPress event programmatically. It supposed to be bad approach as it will trigger all the time.

Then I found a very elegant way to achieve it. There is one property in Form class called CancelButton. So we need to add a button and code there to close it. After that add it as Form’s cancel button and done. But if you have written code to handle ESC key for any other control, this would not work.

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3.     this.Close();
  4. }
  5.  
  6. private void Form1_Load(object sender, EventArgs e)
  7. {
  8.     this.CancelButton = button1;
  9. }

Namoskar!!!

Leave a Comment
  • Please add 1 and 2 and type the answer here:
  • Post
  • Good Morning wriju.

    Which your way you need to have a Button to do your requirement.

    I suggest you to try these others ways:

    1) Change KeyPreview Property of the form to "True". Then you can handle the Form's KeyPress Event.

    2) Overrides the ProcessCmdKey Function.

    If you have any doubt, please email me: rastagar2003@gmail.com

  • Good Morning wriju.

    Which your way you need to have a Button to do your requirement.

    I suggest you to try these others ways:

    1) Change KeyPreview Property of the form to "True". Then you can handle the Form's KeyPress Event.

    2) Overrides the ProcessCmdKey Function.

    If you have any doubt, please email me: rastagar2003@gmail.com

  • @JtorrecillaP,

    Thanks for the refresher. I did post this sometime back in 2008 :) blogs.msdn.com/.../windows-forms-enable-shortcut-key-all-over-the-form.aspx

    I forgot that after it.

  • Hai try these codes both in the keydown and keyup events of the form

    If e.KeyCode = Keys.Escape Then

               Me.Close()

    End If

  • dont use that approach when u have keydown event already...??

  • private void Form1_KeyDown(object sender, KeyEventArgs e)

           {

               if (e.KeyValue.ToString() == "27")

                   Application.Exit();

           }

Page 1 of 1 (6 items)