Keyboard Hook

I wrote a simple hook program that should print out "Key pressed" whenever a key is pressed but whenever I press something the computer freezes for 5 seconds or so and the application doesn't print out anything. Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Keylogger.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <Windows.h>

HHOOK hHook = NULL;

using namespace std;

LRESULT CALLBACK MyLowLevelKeyBoardProc (int nCode, WPARAM wParam, LPARAM lParam) {

	cout << "Key pressed." << endl;

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

int main(int argc, char *argv[])
{
	hHook = SetWindowsHookEx (WH_KEYBOARD_LL, MyLowLevelKeyBoardProc, NULL, 0);
	if (hHook == NULL) {
		cout << "Hook failed." << endl;
	}
	else {
		cout << "Worked."<< endl;
	}

	cin.get();
	return 0;
}


Help me please.
Last edited on
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644985%28v=vs.85%29.aspx

Documentation over guessing. In particular, read the remarks section for what is required for the hook to work.

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.
I replaced cin.get() with while(GetMessage(NULL, NULL, 0, 0)); Is that ok or am I doing something wrong. The program worked and the freezing stopped too.
Last edited on
Topic archived. No new replies allowed.