【问题标题】:Access VBA bit masking in KeyDown Event在 KeyDown 事件中访问 VBA 位掩码
【发布时间】:2018-08-23 16:14:50
【问题描述】:

我希望使用 Access 键事件,但需要更好地了解代码的工作原理。在下面的代码中,我不明白“(Shift And acShiftMask)> 0 ”是如何工作的。如果有人能帮助我理解位掩码以及以下代码的工作原理,我将不胜感激?

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." 

结束子

【问题讨论】:

标签: ms-access vba


【解决方案1】:

Shift 参数包含某些,当KeyDown 事件被触发时,这些位对 SHIFT、CTRL 和 ALT 键的状态进行编码。内置常量 acShiftMask (=1)、acCtrlMask (=2) 和 acAltMask (=4) 仅包含编码(“掩码”)这些特殊键之一的位.按位计算,如下所示:

acShiftMask: 0000000000000001
acCtrlMask : 0000000000000010
acAltMask  : 0000000000000100

现在,如果用户同时按下 SHIFT 和 CTRL 键,Shift 参数将如下所示:

Shift      : 0000000000000011

要检查是否按下了 SHIFT 键,代码必须测试 shift mask 的位,这是通过按位 AND 运算符完成的:

0000000000000011 AND 0000000000000001 = 0000000000000001 (<>0)

这是&lt;&gt;0(实际上比较应该是这样的)。确切地说,比较应该是(Shift And acShiftMask) = acShiftMask,而保存结果的变量可以是Boolean 类型。

无论如何,如果比较成立,则结果不为零,因此按下了特殊键。如果结果为零,如本例中的 ALT 键,则不按下该键:

0000000000000011 AND 0000000000000100 = 0000000000000000 (=0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2018-08-01
    相关资源
    最近更新 更多