Closing a Windows Form by pressing ESC key
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.
- private void button1_Click(object sender, EventArgs e)
- {
- this.Close();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- this.CancelButton = button1;
- }
Namoskar!!!
Comments
- Anonymous
November 03, 2010
Good Morning wriju. Which your way you need to have a Button to do your requirement. I suggest you to try these others ways:
- Change KeyPreview Property of the form to "True". Then you can handle the Form's KeyPress Event.
- Overrides the ProcessCmdKey Function. If you have any doubt, please email me: rastagar2003@gmail.com
- Anonymous
November 03, 2010
Good Morning wriju. Which your way you need to have a Button to do your requirement. I suggest you to try these others ways:
- Change KeyPreview Property of the form to "True". Then you can handle the Form's KeyPress Event.
- Overrides the ProcessCmdKey Function. If you have any doubt, please email me: rastagar2003@gmail.com
Anonymous
November 04, 2010
@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.Anonymous
November 13, 2010
Hai try these codes both in the keydown and keyup events of the form If e.KeyCode = Keys.Escape Then Me.Close() End IfAnonymous
May 15, 2011
dont use that approach when u have keydown event already...??Anonymous
July 13, 2011
private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyValue.ToString() == "27") Application.Exit(); }Anonymous
October 23, 2015
change form property name Keypreview set true and in keyDown event void FrmSaleKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { DialogResult rs = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (rs == DialogResult.No) { return; } Close(); } }