我試圖做一個簡單的鍵盤測試,但我的程序沒有按預期工作,我不知道爲什麼。如何添加一個鉤子到鍵盤(HookProc)
在我的程序中,我有一個低級別的鍵盤掛鉤,並附加一個簡單的過程。該過程只是打開/創建一個文件並寫入「Hello World」,然後關閉。但是它不會創建該文件,可能是因爲我的進程不正確,或者因爲我的鉤子沒有正確建立。
代碼:
#include<windows.h>
#include<stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam){
ofstream myfile;
myfile.open ("[PATH]/example.txt");
myfile << "Hello world";//((KBDLLHOOKSTRUCT *)lParam)->vkCode
myfile.close();
return CallNextHookEx(NULL,code,wParam,lParam);
}
int main(void){
HINSTANCE hInst = NULL;
HHOOK hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, hInst, 0);
printf("HHOOK is not null: %s\n", (hHook != NULL) ? "True" : "False");
char q;
for (cout << "q to quit\n"; q != 'q'; cin >> q);
printf("Successfully unhooked: %s", UnhookWindowsHookEx(hHook) ? "True" : "False");
}
解決方案我需要一個消息循環添加到主功能:
LPMSG Msg;
while(GetMessage(Msg, NULL, 0, 0) > 0)
{
TranslateMessage(Msg);
DispatchMessage(Msg);
}
檢查調用'SetWindowsHookEx'的結果。從MSDN引用:「如果函數失敗,返回值爲NULL。要獲得擴展錯誤信息,請調用GetLastError。」 – bialpio 2014-11-21 20:56:06
它不爲空,我會更新代碼,使其包含檢查 – Alter 2014-11-21 20:59:20
您的解決方案有一個大內存問題!您正在使用指向MSG的指針,但您沒有分配內存來存儲它。你最好使用:MSG Msg;並將它的指針傳遞給每個函數(即&Msg) – cabbi 2014-11-22 05:52:26