Need help with a form's KeyDown event

B

BobV

Group:

Is it possible to use a form's KeyDown event to trap when the user presses
two keys simultaneously, like the Alt key and the letter R, for example? I
would like to trap that event so that I can then activate certain
subroutines. If this can be done, can someone give me a start on
implementing it? Or is there another way to trap the pressing of two keys
simultaneously?

Thank you,
BobV
 
J

John Viescas

Bob-

First, set the form's Key Preview property to Yes - your form KeyDown event
procedure will then see all key presses before they're processed. To check
for Alt-R, do this:

If KeyCode = vbKeyR And ((Shift And acAltMask) > 0) Then
' Swallow the keystroke
KeyCode = 0
' Call your Alt-R code here
End If

--
John Viescas, author
"Microsoft Office Access 2003 Inside Out"
"Running Microsoft Access 2000"
"SQL Queries for Mere Mortals"
http://www.viescas.com/
(Microsoft Access MVP since 1993)
http://www.deanforamerica.com/johnviescas
 
A

Andrew Smith

Yes it can be done.

You need to set the form's key preview property to "True" so that the form
receives all key strokes before the active control. (If you don't do this
the key down event of the form won't fire unless the form itself has the
focus).

The KeyDown event has two arguments, KeyCode and Shift. The value of KeyCode
corresponds to the key that was pressed, and the value of Shift tells you if
the Ctrl, Shift or Alt keys were pressed at the same time. You can convert
KeyCode to a character with the Chr function.

So to tell if someone pressed Alt and R you would use code like this:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

If Shift = acAltMask And Chr(KeyCode) = "R" Then
MsgBox "Alt-R pressed"
End If

End Sub

(Shift has the values acAltMask, acCtrlMask or acShiftMask if Alt, Ctrl or
Shift were pressed when the event occured).
 
B

BobV

Thank you to John and Andrew for your help. This is what I was looking for.
I really appreciate your help.

BobV
 

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