Search code examples
vb.netvisual-studio-express

Closing a VB.NET form when Escape key is pressed


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.


Solution

  • 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.