Moon
Moon

Reputation: 20002

Global Low Level Keyboard Hook for Combinations

i know how to do "Global Low Level Keyboard Hook" thanks to this tutorial.

I also wanted to monitor combination keys or shortcuts,

what my idea was that i could have an array of flags that could represent up\down states of keys of my keyboard.

Simply when a falg is SET or 1 the key is down and when it is UNSET or 0 the key is up.

I can use this for combination keys\shortcuts. When one key is down, the hook will take me to a function in which i will handle the event. What i will to do is, check whether any other particular flag is set. If yes then this means two keys are pressed simultaneously, and thus i have my combination.

I can make this trick work.

What i am looking for is a better option. Is there any.

Upvotes: 0

Views: 1547

Answers (1)

Cody Gray
Cody Gray

Reputation: 244722

Yes, that better option is the RegisterHotKey function.

Global hooks are a very heavy approach and should only be used where absolutely necessary. In this case, it sounds like not only is a global hook unnecessary, but actually more complicated to implement than responding to a simple WM_HOTKEY message automatically generated each time your desired key sequence(s) are pressed.

Since you're using .NET, you will need to P/Invoke the RegisterHotKey function.
The definition looks something like this:

[DllImport("user32.dll", SetLastError = true)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

The WM_HOTKEY message, which you can process by overriding the WndProc method of your form (the one whose handle you specified when calling the RegisterHotKey function, corresponds to the following value:

const int WM_HOTKEY = 0x0312;

The other required values are all clearly provided in the linked documentation for the RegisterHotKey function. The docs are, of course, required reading; otherwise you'll miss important caveats.

Upvotes: 4

Related Questions