全局钩子是要用DLL才能使用的。
因为只有HOOK PROCEDURE在DLL中,才能被windows注射到其他线程的地址空间中。
一个程序总要带着DLL走总是不爽吧,有没有不用DLL就可以使用的全局钩子呢?
当然有的:
WH_KEYBOARD_LL
Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events.
WH_MOUSE_LL
Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events.
这两个记录低级鼠标和键盘消息的钩子就可以在EXE中直接使用而不需要DLL,使用这两个钩子的最低系统要求是Windows NT 4.0 SP3或以上版本。
下面是一个MSDN的例程:(屏蔽Alt+Esc, Ctrl+Esc, Alt+Tab)
/************************************************************************
Module: DisableLowLevelKeys.cpp
Notices: Written 2000 Jeffrey Richter
**************************************************************************/
#define _WIN32_WINNT 0x0400 //当_WIN32_WINNT >= 0x0400时WH_KEYBOARD_LL才有定义
#include <Windows.h>
/
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
BOOL fEatKeystroke = FALSE;
if (nCode == HC_ACTION)
{
switch (wParam)
{
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) lParam;
fEatKeystroke =
((p->vkCode == VK_TAB) && ((p->flags & LLKHF_ALTDOWN) != 0)) ||
((p->vkCode == VK_ESCAPE) &&
((p->flags & LLKHF_ALTDOWN) != 0)) ||
((p->vkCode == VK_ESCAPE) && ((GetKeyState(VK_CONTROL) &
0x8000) != 0));
break;
}
}
return(fEatKeystroke ? 1 : CallNextHookEx(NULL, nCode, wParam, lParam));
}
/
int WINAPI WinMain(HINSTANCE hinstExe, HINSTANCE, PTSTR pszCmdLine, int)
{
// Install the low-level keyboard & mouse hooks
HHOOK hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hinstExe, 0);
// Keep this app running until we're told to stop
MessageBox(NULL,
TEXT("Alt+Esc, Ctrl+Esc, and Alt+Tab are now disabled./n")
TEXT("Click /"Ok/" to terminate this application and re-enable these keys."),
TEXT("Disable Low-Level Keys"), MB_OK);
UnhookWindowsHookEx(hhkLowLevelKybd);
return(0);
}