Visual Basic Concepts
Detecting SHIFT, CTRL, and ALT States
The mouse and keyboard events use the shift argument to determine whether the SHIFT, CTRL, and ALT keys are pressed and in what, if any, combination. If the SHIFT key is pressed, shift is 1; if the CTRL key is pressed, shift is 2; and if the ALT key is pressed, shift is 4. To determine combinations of these keys, use the total of their values. For example, if SHIFT and ALT are pressed, shift equals 5 (1 + 4).
The three least-significant bits in shift correspond to the state of the SHIFT, CTRL, and ALT keys, as shown in Figure 11.5.
Figure 11.5 How bits represent the state of the SHIFT, CTRL, and ALT keys
Any or all of the bits in shift can be set, depending on the state of the SHIFT, CTRL, and ALT keys. These values and constants are listed in the following table:
|Binary Value||Decimal Value||Constant||Meaning|
|001||1||vbShiftMask||The SHIFT key is pressed.|
|010||2||vbCtrlMask||The CTRL key is pressed.|
|100||4||vbAltMask||The ALT key is pressed.|
|011||3||vbShiftMask + vbCtrlMask||The SHIFT and CTRL keys are pressed.|
|101||5||vbShiftMask + vbAltMask||The SHIFT and ALT keys are pressed.|
|110||6||vbCtrlMask + vbAltMask||The CTRL and ALT keys are pressed.|
|111||7||vbCtrlMask + vbAltMask + vbShiftMask||The SHIFT, CTRL, and ALT keys are pressed.|
As with the mouse events' button argument, you can use the If…Then…Else statement or the And operator combined with the Select Case statement to determine whether the SHIFT, CTRL, or ALT keys are being pressed and in what, if any, combination.
Open a new project and add the variable
ShiftTest to the Declarations section of the form:
Dim ShiftTest as Integer
Add the following code to the form's MouseDown event:
Private Sub Form_MouseDown(Button As Integer, _ Shift As Integer, X As Single, Y As Single) ShiftTest = Shift And 7 Select Case ShiftTest Case 1 ' or vbShiftMask Print "You pressed the SHIFT key." Case 2 ' or vbCtrlMask Print "You pressed the CTRL key." Case 4 ' or vbAltMask Print "You pressed the ALT key." Case 3 Print "You pressed both SHIFT and CTRL." Case 5 Print "You pressed both SHIFT and ALT." Case 6 Print "You pressed both CTRL and ALT." Case 7 Print "You pressed SHIFT, CTRL, and ALT." End Select End Sub