我试图实现一个记录键击的简单程序,我按照教程进行操作,最后得到了这个:
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <Windows.h>
static HHOOK hkb;
static FILE* f1;
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
char c;
std::cout << "inside hook" << std::endl;
if (((DWORD)lParam & 0x40000000) && (HC_ACTION == nCode))
{
if ((wParam == VK_SPACE) || (wParam == VK_RETURN) || (wParam >= 0x2f) && (wParam <= 0x100))
{
f1 = fopen("report.txt", "a");
std::cout << "inside if good" << std::endl;
if (wParam == VK_RETURN)
{
c = '\n';
fwrite(&c, 1, 1, f1);
}
else
{
BYTE ks[256];
GetKeyboardState(ks);
WORD w;
UINT scan = 0;
ToAscii(wParam, scan, ks, &w, 0);
c = (char)w;
fwrite(&c, 1, 1, f1);
}
fclose(f1);
}
}
LRESULT RetVal = CallNextHookEx(hkb, nCode, wParam, lParam);
return RetVal;
}
BOOL installhook()
{
f1 = fopen("report.txt", "w");
fclose(f1);
hkb = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc, NULL, GetCurrentThreadId());
if (hkb == NULL)
{
std::cerr << "failed to set hook" << std::endl;
return false;
}
return true;
}
int main()
{
installhook();
std::cin.get();
return 0;
}
钩子显然设置正确,但是当我输入内容时它没有被调用,因此没有达到我在KeyboardProc()中的测试std :: cout。
当然我错过了一些东西或者没理解钩子是如何工作的。