How do I use low-level 8 bit flags as conditionals?

微笑、不失礼 提交于 2019-12-05 07:47:10

You need to bitwise-and it with a mask. For example, the injected bit is bit 4. That's binary 00010000, hex 0x10. So you bitwise-and it with 0x10, and see if anything's left:

bool isInjected = ((kbd.flags & 0x10) != 0);

(Of course, as per Andrew's answer, it would be a good idea to define a LLKHF_INJECTED constant for this rather than including the hex value directly in your code!)

Hans Passant

.NET supports this with the [Flags] attribute:

[Flags]
enum KbdHookFlags {
  Extended = 0x01,
  Injected = 0x10,
  AltPressed = 0x20,
  Released = 0x80
}

Sample usage:

  KBDLLHOOKSTRUCT info = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
  if ((info.flags & KbdHookFlags.Released) == KbdHookFlags.Released) {
    // Key was released
    // etc..
  }

Use the bitwise AND operator to check if the relevant bit is set in the flags variable:

if (kbd.flags & LLKHF_INJECTED)
{
    ...
}
Skurmedel

You need to check that the bitflag is set. Easy to do with bitwise operations. The documentation states that bit four is used for the injected flag, bit 4 (or 5 if you count the first bit as 1) equals 16, so you can do a bitwise AND against the flag.

if ((kbd.flags & 16) == 16)
{
    FireTorpedoes();
}

You can learn more about bitwise operations here:

The reason everyone is saying to use a bitwise & and then compare to zero or the flag:

  0111 1000        // kbd.flags 
& 0001 0000        // Injected
          =
  0001 0000        // (!= 0 or ==Injected)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!