Michael Rodenbaugh
Michael Rodenbaugh

Reputation:

C#: Which is the best hook to use to monitor multiple-key shortcuts globally?

There is LowLevelKeyboardProc and KeyboardProc. I want to monitor key-combinations such as Alt+Q globally in Windows and perform an action based on Alt+Q being pressed. Which hook would be the best option to use and how would I go upon detecting if all the keys in the hotkey are currently being held down as opposed to monitoring each key one by one in the hook callback?

Upvotes: 1

Views: 810

Answers (2)

George Mamaladze
George Mamaladze

Reputation: 7931

As stated in the answer by Hans Passant, technically there is no way except attaching to WH_KEYBOARD_LL hook. Nevertheless there is a managed library MouseKeyHook as nuget which gives you a convenience managed wrapper. Source code on github.

Recently support for detecting shortcuts, key combinations and sequences was added. Here is a usage example:

void DoSomething()
{
    Console.WriteLine("You pressed UNDO");
}

Hook.GlobalEvents().OnCombination(new Dictionary<Combination, Action>
{
    {Combination.FromString("Control+Z"), DoSomething},
    {Combination.FromString("Shift+Alt+Enter"), () => { Console.WriteLine("You Pressed FULL SCREEN"); }}
});

For more information see: Detecting Key Combinations and Seuqnces

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941377

You don't have a choice, WH_KEYBOARD_LL is the only one you can write in C#. WH_KEYBOARD requires writing a DLL that can be injected in another process. Not possible with managed code, the CLR cannot be initialized properly.

Also consider RegisterHotKey(). Sample code is there, you'll find C# further down the page.

Upvotes: 2

Related Questions