Closing a VB.NET form when Escape key is pressed

whytheq picture whytheq · Nov 22, 2012 · Viewed 39.2k times · Source

I'm using VB 2010 Express.

In C# I would set the forms CancelButton property.

For this VB form I don't have a CancelButton so I suspect I need to program either KeyPress or KeyDown.

  1. What is the difference between these two events?
  2. Which should I use?
  3. I assume the general code for this is as follows?:

    If e.KeyCode = Keys.Escape Then
        Close()
    End If
    

I have certain .Focus code within other controls of the form then it becomes pointless putting this in the main forms event procedure as the main form never really has the focus.

Answer

Patrick Guimalan picture Patrick Guimalan · Nov 22, 2012

Set your form keydown to

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.Escape Then Me.Close()
End Sub

Then, Remember to set the KeyPreview property on the form to TRUE.