i've created this keylogger using win api.
int keylogger_main()
{
char path[] = "D:\\winApiFiles\\key_logs.txt";
// delete the previous file, always.
DeleteFileA(path);
MSG msg;
HHOOK hHook = NULL;
// starting time
time_t start_time = time(NULL);
// setting hook
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, kbHook, NULL, 0);
if (hHook == NULL)
{
printf("HOOK FAILED");
}
while (GetMessage(NULL, NULL, 0, 0));
printf("Key logs saved to: %s", path);
return 0;
}
This is just the main. the kbHook LRESULT works fine. When I run it like this, it works and saves the key logs to the file. But I want the program to stop after a certain amount of time.
I tried using sleep and UnhookWindowsHookEx before the call to while:
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, kbHook, NULL, 0);
if (hHook == NULL)
{
printf("HOOK FAILED");
}
Sleep(10000);
UnhookWindowsHookEx(hHook);
while (GetMessage(NULL, NULL, 0, 0));
But for some reason, the hook doesn't work until the GetMessage function is called. So because I unhook the hook before GetMessage is called, no key log file is created (I don't understand why). And when it is called, it is stuck. Because for some reason, no messages are available in the message queue.
If someone could explain to me what is happening, I'll be very greatful.
GetMessage()blocks the calling thread until a posted message is available in that thread's message queue, while dispatching synchronous window messages from other threads. MostSetWindowsHookEx()hooks use internal messages and thus require the installing thread to have an active message loop to dispatch hook events. This is even stated in the LowLevelKeyboardProc callback function documentation:To implement a timeout mechanism in a message loop, you can use a Waitable Timer in combination with
MsgWaitForMultipleObjects(), eg:Alternatively, you can just use the timeout parameter of
MsgWaitForMulipleObjects()and not use a waitable timer at all, eg: