Chinese version author: peach@newsmth.net
Userally, when you install a global hook, you need a dll. But now, you can install WH_KEYBOARD_LL or WH_MOUSE_LL global hook without dll’s help.
The following code was tested under win2k3. And I it will also run on 2k/xp.
#define _WIN32_WINNT 0400
#define STRICT
#define WIN32_LEAN_AND_MEAN
#include
#include
#include
DWORD g_main_tid = 0;
HHOOK g_kb_hook = 0;
BOOL CALLBACK con_handler (DWORD)
{
PostThreadMessage (g_main_tid, WM_QUIT, 0, 0);
return TRUE;
};
LRESULT CALLBACK kb_proc (int code, WPARAM w, LPARAM l)
{
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)l;
const char *info = NULL;
if (w == WM_KEYDOWN)
info = “key dn”;
else if (w == WM_KEYUP)
info = “key up”;
else if (w == WM_SYSKEYDOWN)
info = “sys key dn”;
else if (w == WM_SYSKEYUP)
info = “sys key up”;
printf (“%s – vkCode [%04x], scanCode [%04x]\n”,
info, p->vkCode, p->scanCode);
// always call next hook
return CallNextHookEx (g_kb_hook, code, w, l);
};
int main (void)
{
g_main_tid = GetCurrentThreadId ();
SetConsoleCtrlHandler (&con_handler, TRUE);
g_kb_hook = SetWindowsHookEx (
WH_KEYBOARD_LL,
&kb_proc,
GetModuleHandle (NULL), // It shouldn’t be NULL, or will fail
0);
if (g_kb_hook == NULL)
{
fprintf (stderr,
“SetWindowsHookEx failed with error %d\n”,
::GetLastError ());
return 0;
};
// The message loop is necesarry
MSG msg;
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
};
UnhookWindowsHookEx (g_kb_hook);
return 0;
};
Permalink: Code Library - Install global hook without dll
Subcribe the update with Google Reader.
2 Responses
Thomas
November 6th, 2009 at 2:28 am
1Thank you!
This helps a lot!
Mohammad
May 13th, 2010 at 4:08 am
2Thanks. This saved a big project from some bad bugs.
RSS feed for comments on this post · TrackBack URI
Leave a reply
Category
Recent Posts
Hot Posts
Creative Commons
Code Library