Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Ctrl and S in Keydown event

Status
Not open for further replies.

EddyLLC

Technical User
Mar 15, 2005
304
US
Is it possible to use the Keydown event with a key press combination of Ctrl and S?

I want to press Ctrl and S to start the event. Thanks
 
Give this a shot

Code:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyS And Shift = 2 Then
        MsgBox "Ctrl and S Was pressed"
    End If
End Sub


The Shift variable explained: An integer that corresponds to the state of the SHIFT, CTRL, and ALT keys at the time of the event. The shift argument is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2 ). These bits correspond to the values 1, 2, and 4, respectively. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys are pressed. For example, if both CTRL and ALT are pressed, the value of shift is 6.
[thumbsup]
 
I think that might be slightly improved as:
Code:
[blue]Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyS And Shift = [b]vbCtrlMask[/b] Then
        MsgBox "Ctrl and S Was pressed"
    End If
End Sub[/blue]

since this gets rid of the magic number, and make the code more readable. vbAltMask and vbShiftMask represent the other possibilities.

Using your example of checking for CTRL and ALT, I'd argue that

[tt]If Shift = vbAltMask + vbShiftMask ...[/tt]

(or, more properly, [tt]If Shift = vbAltMask Or vbShiftMask[/tt])

is easier to understand than

[tt]If Shift = 6 ...[/tt]
 
Yes indeed the shift constants,

vbShiftMask = 1 'SHIFT key bit mask.
VbCtrlMask = 2 'CTRL key bit mask.
VbAltMask = 4 'ALT key bit mask.

make the code more readable.
 
Splendid! The code works perfect. Thanks so much for the help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top