extern "C" __declspec(dlleXPort) void __stdcall SetHook(HWND,bool);
LRESULT CALLBACK HookProc(int nCode,WPARAM wParam,LPARAM lParam)
static HINSTANCE hInstance; // 应用实例句柄
static HWND hWndMain; // MainForm句柄
static HHOOK hKeyHook; // HOOK句柄
static const myMessage=2000; // 自定义消息号
static const SecondPar=1; // 自定义消息第2参数
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{ hInstance=hinst; return 1; }
void __stdcall SetHook(HWND hMainWin,bool nCode)
{
if(nCode) // 安放HOOK
{
hWndMain=hMainWin;
hKeyHook=SetWindowsHookEx(WH_JOURNALRECORD,(HOOKPROC)HookProc,hInstance,0);
}
else // 卸下HOOK
UnhookWindowsHookEx(hKeyHook);
}
LRESULT CALLBACK HookProc(int nCode,WPARAM wParam,LPARAM lParam)
{
EVENTMSG *keyMSG=(EVENTMSG *)lParam;
if((nCode==HC_ACTION)&&(keyMSG->message==WM_KEYUP))
PostMessage(hWndMain,myMessage,(char)(keyMSG->paramL),SecondPar);
// 向调用窗体发消息myMessage和虚拟键码(char)(keyMSG->paramL)
return((int)CallNextHookEx(hKeyHook,nCode,wParam,lParam));
}
static HINSTANCE hDLL; // DLL句柄
typedef void __stdcall (*DLLFUN)(HWND,bool);
DLLFUN DLLSetHook;
static const myMessage=2000;
static const SecondPar=1;
__fastcall TForm1::TForm1(TComponent* Owner):TForm(Owner)
{}
简单实现:键盘全局钩子,监视多进程键盘操作。