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

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
 
A

Armin Zingler

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
 
K

kimiraikkonen

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
 
J

John Sheppard

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
 
J

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top