Close a form by pressing esc, how to do it without having a button

  • Thread starter Thread starter John Sheppard
  • Start date Start date
J

John Sheppard

Hello there,

I was wondering if anyone knew how to close a form when the user presses the
esc key. I dont have any buttons on the form so I cannot use the
cancelButton property of the form.

I have tried using the forms keypressed event but it doesnt seem to be
firing. Does anyone have any suggestins?

Thank you
John Sheppard
 
John Sheppard said:
Hello there,

I was wondering if anyone knew how to close a form when the user
presses the esc key. I dont have any buttons on the form so I cannot
use the
cancelButton property of the form.

I have tried using the forms keypressed event but it doesnt seem to
be firing. Does anyone have any suggestins?

Set the Form's keypreview property = True and handle it's keydown event.
I assume you want to handle key strokes, not char input.


Armin
 
Hello there,

I was wondering if anyone knew how to close a form when the user presses the
esc key. I dont have any buttons on the form so I cannot use the
cancelButton property of the form.

I have tried using the forms keypressed event but it doesnt seem to be
firing. Does anyone have any suggestins?

Thank you
John Sheppard

John,
Normally adding a hidden but and assing cancelButton value would be
shortest way, but still if you don't want to add any button, here is
your solution:

First, set Form's KeyPreview value to "True" from properties window,
then:

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

Hope this helps,

Onur Güzel
 
Armin Zingler said:
Set the Form's keypreview property = True and handle it's keydown event. I
assume you want to handle key strokes, not char input.


Armin


Ahh the keypreview property....I missed that...

Thanks so much Armin, very much appreciate your help
John Sheppard
 
John,
Normally adding a hidden but and assing cancelButton value would be
shortest way, but still if you don't want to add any button, here is
your solution:

First, set Form's KeyPreview value to "True" from properties window,
then:

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

Hope this helps,

Onur Güzel

Heh yeah I dont like the hidden button...its a clunk...The keypreview
property was what I was missing out on...
Thanks so much, very much appreciate your time to help
John Sheppard
 
Back
Top