Hi Everyone,
What is the code that when you hit the "Esc" key, the program will end?
Thanks in advance.
Printable View
Hi Everyone,
What is the code that when you hit the "Esc" key, the program will end?
Thanks in advance.
Simple way
in the form properties.. set KeyPreview = True
VB Code:
Private Sub Form_KeyPress(KeyAscii As Integer) If KeyAscii = 27 Then Unload Me End Sub
Another way is to drop a standard command button on the form and enter 'Close' as its Caption property and have Unload Me in its click event. Then set the control's Cancel property to True. When you do, VB executes this button's Click() event whenever you press the [Esc] key (as well as when you click it).
Or...
I use this thread, to ask another question:VB Code:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) If KeyCode = vbKeyEscape Then Unload Me End If End Sub
Is there a difference between KeyDown and KeyPress ?
Thanks guys. That worked. Much appreciated.
Yes, but they can refer to the same key.Quote:
Originally Posted by DubweiserTM
For example, the KeyCode for "A" is vbKeyA and this would be used in the KeyDown event.
The KeyAscii code for "A" is 65, so using KeyAscii Chr(65) in the Keypress event would be the same as using vbKeyA in the KeyCode of event of Keydown. It is confusing, I know.
Start up a standard exe project with a single textbox and do some tests.Play with pressing the various keys on the keyboard and the numeric keypad and the function keys. You'll see that KeyDown always gives you results. KeyPress only gives you results when there is a valid ASCII character being generated. In addition, the KeyAscii and KeyCode values don't always match, but some, if not most, are similar enough to be confusing.VB Code:
Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer) Debug.Print "KeyDown value: " & KeyCode End Sub Private Sub Text1_KeyPress(KeyAscii As Integer) Debug.Print """Ascii " & KeyAscii & " = " & Chr(KeyAscii) End Sub
Thanks Hack for explaining that to me. Very interesting.
Thanks for this lesson ! :thumb:Quote:
Originally Posted by Hack
Another "gotcha" with ascii codes is there are different codes for capital and small letters.
Example: A = Chr(65)
a = Chr(97)
vbKeyA doesn't care whether you chose a capital or a small, so when dealing with single letters (like making a hot key combination), I always use the KeyCode.