I want to capture user keyboard input to react well on keyboard media keys: play/pause, next and previous in particular. I tried to use SetWindowsHookEx with low-level WH_KEYBOARD_LL param to ensure I can get maximum responsibility from this WINAPI function, and I stucked with nothing. If I set breakpoint in hook callback, debugger stops on any keyboard event when I hit regular keys, such as letters or F modifiers, but it never stops when I hit one of media keys, such as Play/Payse. I tried to download demo applications which demonstrate usage of SetWindowsHookEx and none of it works with MM keys. Also I have read this single related question, but there is no answers in it.
I used this piece of code to set up hook:
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYUP = 0x0101;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
public static IntPtr SetHook()
{
using (var curProcess = Process.GetCurrentProcess())
{
using (var curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
}
public static void UnsetHook()
{
UnhookWindowsHookEx(_hookID);
}
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYUP)
{
int vkCode = Marshal.ReadInt32(lParam);
Debug.WriteLine((Keys)vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
I found info that RegisterHotKey
should help in my task, but since I want react on regular keys too, it will be much comfortable to work with one API member for all regular and MM keys. Is this dead approach or I missing something?