Reputation: 65
I'm hoping to use the Access key events but need to better understand how the code works. In the below code I don't understand how "(Shift And acShiftMask) > 0 " is working. I Would appreciate it if someone could help me understand bit masks and how the below code works?
Private Sub KeyHandler_KeyDown(KeyCode As Integer, _
Shift As Integer)
Dim intShiftDown As Integer, intAltDown As Integer
Dim intCtrlDown As Integer
' Use bit masks to determine which key was pressed.
intShiftDown = (Shift And acShiftMask) > 0
intAltDown = (Shift And acAltMask) > 0
intCtrlDown = (Shift And acCtrlMask) > 0
' Display message telling user which key was pressed.
If intShiftDown Then MsgBox "You pressed the SHIFT key."
If intAltDown Then MsgBox "You pressed the ALT key."
If intCtrlDown Then MsgBox "You pressed the CTRL key."
End Sub
Upvotes: 0
Views: 1792
Reputation: 4100
The Shift
argument contains certain bits that encode the status of the SHIFT, CTRL and ALT keys when the KeyDown
event is fired. The built-in constants acShiftMask
(=1
), acCtrlMask
(=2
) and acAltMask
(=4
) contain ony the bit that encodes ("masks") one of these special keys. Bitwise, this looks like this:
acShiftMask: 0000000000000001
acCtrlMask : 0000000000000010
acAltMask : 0000000000000100
Now, if the user presses a key together with the SHIFT and CTRL keys, the Shift
argument will be as follows:
Shift : 0000000000000011
To check whether the SHIFT key is pressed, the code must test the bit of the shift mask, which is done with the bitwise AND
operator:
0000000000000011 AND 0000000000000001 = 0000000000000001 (<>0)
which is <>0
(in fact the comparison should look like this). To be exact, the comparison should be (Shift And acShiftMask) = acShiftMask
, and the variable holding the result could be of type Boolean
.
Anyway, if the comparison holds, the result isn't zero, so that special key is pressed. If the result is zero, as with the ALT key in this example, the key is not pressed:
0000000000000011 AND 0000000000000100 = 0000000000000000 (=0)
Upvotes: 1