Global hooks that do not depend on DLL
I don't know what everyone has learned by hook, I have seen the "Windows Advanced Programming Guide" Jeffrey Richter (new version of Chinese). "Windows Core Programming"). In this book, the author introduces three ways to inject the code into other processes, one is the global message hook used. I am from this book to the global hook has the initial understanding.
Everyone should know that the global message hook to reluctance to work properly. So, I also think that the global hook can rely on a DLL to work properly, I think that most people will definitely think so.
But it is actually not the case. Some global hooks can work normally without relying on any DLL. These hooks include, wh_journalplayback, wh_journalrRecord, wh_keyboard_ll, wh_mouse_ll. Why can these hooks do not depend on DLL? We can get answers from MSDN, which describes this four hooks in MSDN, "this hook is caled in the context of the thread there", translated into Chinese means calling the hook function is installed in the installation hook The thread context is made, it is more clear that these hooks are installed in which thread is installed, which thread is executed in. So use these four hooks that can not reach the effect of code injection, of course, can not depend on any DLL. Only the individual hooks must be pointed out in the MSDN.
Here is the code example of a base keyboard hook I give, of course, no DLL is required.
/ *
Kbhook.cpp
* /
#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), / / cannot be null, otherwise failed
0);
IF (g_kb_hook == NULL)
{
FPRINTF (stderr,
"SETWINDOWSHOKEX FAILED with ERROR% D / N",
:: getLastError ());
Return 0;
}
// Message loop is necessary, I want to know the reason can check MSDN
MSG msg;
While (GetMessage (& MSG, NULL, 0, 0))
{
TranslateMessage (& MSG);
DispatchMessage (& MSG);
}
UnHookWindowsHookex (g_kb_hook);
Return 0;
}