-
in a current project, in the keypress events of the majority of the controls, I have
Code:
If KeyAscii = vbKeyEscape Then
Call cmdExit_Click
End If
so that whenever the user hits the escape key, the code in cmdExit_Click fires and then the form unloads. It works fine as is, but multiply 3 lines of code times the total number of controls in my project and I have an astronomical amount of code dedicated to unloading forms with the escape key.
My question - is there any way to slim down the amount of code and have the same effects? As in, a module or function or something that will fire when the user presses the escape key, no matter which control has the focus? I am thinking that it is not possible since so much of the functionality of VB is driven by which control has the current focus, but I thought I would give you computer brains here a try anyway. IS this possible, or am I dreaming the impossible?
Thanks
Andrew
-
Use End instead of Call cmdExit_Click. If you have some complex code in there, than put that code in a Module so you can re-use it anywhere.
-
I don't want to end the entire program in all cases. I just want to close the window. Plus all of the code, module calls, and function calls that are needed for each particular window are located in the cmdEnd_Click routine. Like I said, the code already works fine but is repeated many times (once per control). If someone knows how I could invoke a function or module with the escape key no matter which control has the focus, then I could lessen the size of the program considerably. If not, then all's well that ends well, i guess..
-
Or you could do something like so:
In a Module:
Code:
Public Sub ExecuteUnload(ByRef thisform As Form, ByVal ASCIIKey As Byte)
'' check for the ESC key press
'' if pressed, call the forms unload
If (ASCIIKey = vbKeyEscape) Then
Call Unload(thisform)
End if
End Sub
So now you would just use ExecuteUnload(Me, KeyAscii)
and move your exit code into the forms Unload event
-
If that works then it would at least reduce the 3 lines of code per control to one per control (the function call). I'll have to give that a try soon, pending other suggestions?
-
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeyEscape: Unload Me
End Select
End Sub
Private Sub Form_Load()
KeyPreview = True
End Sub
-
that did it!!
CyberCarsten's example works beautifully. Thanks man!
Andrew
-