Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my keyboard hook, each keypress gets a flag that states if it was injected or not. http://msdn.microsoft.com/en-us/library/ms644967(VS.85).aspx

I've distilled a KBDLLHOOKSTRUCT from the lParam. I can access kbd.flags.XXX. I just don't know how to convert this 8bit flag into an if (injected) {... type conditional that I know how to use.

If one of you smart computer-science types would help me out I'd really appreciate it.

    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        KBDLLHOOKSTRUCT kbd = new KBDLLHOOKSTRUCT();
        Marshal.PtrToStructure(lParam, kbd);

        //if (injected) {...

Cheers!

like image 463
ck_ Avatar asked Jan 16 '10 01:01

ck_


2 Answers

.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..
  }
like image 180
Hans Passant Avatar answered Sep 28 '22 01:09

Hans Passant


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!)

like image 22
itowlson Avatar answered Sep 28 '22 01:09

itowlson