假设您使用的是Windows,并且您希望捕获全局击键,那么我将在此处解决问题.一种方法是使用LowLevelHooks.请看以下示例:
在代码中的某处定义此回调函数:
//The function that implements the key logging functionality
LRESULT CALLBACK LowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam )
{
char pressedKey;
// Declare a pointer to the KBDLLHOOKSTRUCTdsad
KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *)lParam;
switch( wParam )
{
case WM_KEYUP: // When the key has been pressed and released
{
//get the key code
pressedKey = (char)pKeyBoard->vkCode;
}
break;
default:
return CallNextHookEx( NULL, nCode, wParam, lParam );
break;
}
//do something with the pressed key here
....
//according to winapi all functions which implement a hook must return by calling next hook
return CallNextHookEx( NULL, nCode, wParam, lParam);
}
然后在你的main函数中的某个地方你可以像这样设置钩子:
//Retrieve the applications instance
HINSTANCE instance = GetModuleHandle(NULL);
//Set a global Windows Hook to capture keystrokes using the function declared above
HHOOK test1 = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, instance,0);
有关挂钩的更多一般信息可以在here找到.
您也可以按照SetWindowsHooksEX文档中给出的说明以相同的方式捕获其他全局事件.