Problem with keyboard hook

Started by
1 comment, last by Cauthon 19 years, 7 months ago
I'm using a global keyboard hook, here is my HookProc:

HOOK_API LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	if(nCode == HC_ACTION && lParam & 0x80000000)
	{
		g_hWnd = FindWindow("#32770", "My Window");
		PostMessage(g_hWnd, WM_USER + 100, wParam, lParam);
	}

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

This works fine for the most part, but the seems to send the message when the key is up rather than down, causing problems such as pressing shift then a letter and recieving the letter before the shift. The problem is probably that I am ANDing lParam with the wrong thing, but I can't figure out what to AND it with to get the correct behavior. Anyone know?
Advertisement
SHORT GetAsyncKeyState(int vKey);

You need to check the state of the key twice to determine if it has been pressed, not once (pressing a key and releasing it are different events, during which other events can happen), for example, clicking and holding the mouse button on a button, then hitting escape will cancel the original click (in most programs).
With the flag 0x80000000 you're checking the state of bit 31. That is the transition bit, and it's the correct bit to check, but you need to know that bit 31 is set to 1 when the key is released. It's 0 when the key is pressed, so just check for bit 31 being 0:
if(nCode == HC_ACTION && !(lParam & 0x80000000)) {}
There are a few other interesting bits in that mask... you may be interested in the repeat count:
unsigned short rptCount = (lParam & 0xFFFF); // See also: LOWORD() macro

This topic is closed to new replies.

Advertisement