Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 797
whytheq Avatar asked Nov 22 '12 09:11

whytheq


People also ask

How do you close a form in VB net?

If you want to close the form then use Me. Close() instead. The Load event will fire again when you create the new instance. You'll have to change a setting to ensure that doesn't also close your application.

Which property is used to exit close the form when pressed Esc?

Set the CancelButton property of the form to that button. Gets or sets the button control that is clicked when the user presses the Esc key. You will also have to set the KeyPreview property to true.

How do I cancel a form closing in VB net?

The event can be canceled by setting the Cancel property to true. Inside the FormClosing event.


2 Answers

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.

like image 185
Patrick Guimalan Avatar answered Sep 24 '22 05:09

Patrick Guimalan


My solution is also in the form properties:

  • set the CancelButton Property to button that performs your cancel function
like image 21
My Brain Avatar answered Sep 25 '22 05:09

My Brain