我看了一下唯一的构造函数,globalKeyboardHook
看起来它只是为全局钩子设计的。您可以像这样添加另一个重载以挂钩到当前正在运行的模块中:
class globalKeyboardHook {
[DllImport("kernel32")]
private static extern int GetCurrentThreadId();
[DllImport("user32")]
private static extern IntPtr SetWindowsHookEx(int hookType, KeyBoardProc proc, IntPtr moduleHandle, int threadId);
[DllImport("user32")]
private static extern int CallNextHookEx(IntPtr hHook, int nCode, IntPtr wParam, IntPtr lParam);
public globalKeyboardHook(bool currentModuleOnly){
if(currentModuleOnly){
proc = KeyBoardCallback;
//WH_KEYBOARD = 0x2
hhook = SetWindowsHookEx(2, proc, IntPtr.Zero, GetCurrentThreadId());
} else hook();
}
public delegate int KeyBoardProc(int nCode, IntPtr wParam, IntPtr lParam);
public int KeyBoardCallback(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode >= 0) {
Keys key = (Keys)wParam;
var lp = lParam.ToInt64();
//your own handling with the key
if ((lp >> 31) == 0)//Key down
{
//your own code ...
} else { //Key up
//your own code ...
}
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
KeyBoardProc proc;
//other code ...
}
//then use the new overload constructor instead of the parameterless constructor:
globalHook = new globalKeyboardHook(true);
注意:您可以根据我上面发布的内容(评论)实施您自己的KeyDown
和事件。经过一番搜索,我了解到仅支持全局钩子,而仅用于。那应该是您想要的,而不是.KeyUp
your own code ...
WH_KEYBOARD_LL
WH_KEYBOARD
thread hook
WH_KEYBOARD_LL
顺便说一句,我怀疑IMessageFilter
在这种情况下可以使用您的应用程序注册/添加的内容。它还支持一种PreFilterMessage
方法,可帮助您拦截application-level
. 您应该尝试搜索它,这很容易理解。