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.

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