I want to Hook a specific control (a combobox) and receive all keys typed in that control. The Combobox is part of an Outlook Ribbon an has no events like keypress or something (just onChange which behaves really weird).
Here is the Code:
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private LowLevelKeyboardProc _proc;
private IntPtr _hookID = IntPtr.Zero;
private void SetHook(IntPtr handle)
{
uint PID; //not needed
_proc = HookCallback;
uint threadid = GetWindowThreadProcessId(handle, out PID);
_hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, IntPtr.Zero, threadid );
}
private delegate IntPtr LowLevelKeyboardProc(
int nCode, IntPtr wParam, IntPtr lParam);
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
System.Diagnostics.Debug.WriteLine("Key: " + (Keys)vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
The handle i have and the ThreadID i get are correct (verified via Spy++) but no key is captured. Works fine with “0” as the last parameter of the SetWindowsHookEx function but then its a global hook ofcourse.
I add this for anyone who has the same problem. Keyboardhooks are global, one cannot hook to a specific control. What you need to do is capture the messages of the given handle. To do so, you have to subclass your window/handle.