Close a form with [Esc] or Chr(27)

ravenge

Member
Joined
Mar 18, 2005
Messages
13
Programming Experience
Beginner
[RESOLVED] - Close a form with [Esc] or Chr(27)

Hi, this is probably really easy but I am trying to close a form with the esc key.

This is the code I have but it isn't working.

VB.NET:
Private Sub frm_main_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
		If e.KeyChar = Chr(27) Then
			me.close
		End If
	End Sub

Can anyone please help me with this.

Thanks in advance
JB
 
Last edited:
PHP:
 If e.KeyChar = Chr(27) Then 
 
Me.Close()
 
End If


looks fine to me ... except you can't find the focus of the form ... try to add a certain code to any other control (textbox, combobox ...or simply pass all controls within current form - for each xControl in me.Controls ...) and see by yourself that it will work. Or as ECPM told you:
PHP:
 If e.KeyValue = e.KeyCode.Escape Then 
 
Me.Close()
 
End If


Cheers ;)
 
Another easy way to close the form with esc key is to create a button label it 'close' and set Form's cancelbutton properity to it.....and write 'Me.close' in button's click event.......Very simple
 
the KeyPress event for a form only gets called if the KeyPreview property is set to true

but a form's KeyDown event is always called (even if keypreview is set to false)

so in the form's KeyDown (or KeyUp) event put:

If e.KeyCode = Keys.Escape Then Me.Close
 
thanks to all that helped. I took a bit from everyone and this is my resolution

Changed the forms keypreview = true and used this code in forms keypress action

VB.NET:
If e.KeyChar.ToString = Chr(27) Then
			Me.Close()
		End If

Thanks again all that helped :)
 
Back
Top