How do I assign a hotkey in a form?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a simple switchboard form that has two buttons - a 'Yes' and a 'No'.
In testing it, I found myself automatically hitting the 'y' key on the
keyboard instead of using the mouse and clicking the button. Is there a way
to set a hotkey behind the scenes for both 'y' and 'n' just on this form?
Causing a keystroke to do the same thing the buttons do...

Thanks in advance for any help!

Parker
 
There are two ways to do this - one would be to use the built-in method for
creating keyboard shortcuts. Open the property sheet of the command button
and put an & character in front of the "Y" in "Yes" in the caption property.
This will underscore the letter "Y" and allow you to use Alt-Y as a keyboard
shortcut to hit the button.

The other option is to trap the keyboard input by using the KeyDown event.
Note that this will render the "Y" and "N" keys useless on the form except
for simulating a button click. First, make sure that the Keypreview property
of the form is set to True then use code similar to the following:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyY then
'do whatever the button does or call the same code
MsgBox "Click Yes"
Keyode = 0
Else if KeyCode = vbKeyN then
'do whatever the button does or call the same code
MsgBox "Click No"
Keyode = 0
End If
End Sub
 
Back
Top