代码如下:
extern "C" __declspec(dllexport) void __stdcall SetHook(HWND,bool);
LRESULT CALLBACK HookProc(int nCode,WPARAM wParam,LPARAM lParam);
//----------------------------------------------------------------------------------------------------
static HINSTANCE hInstance; // 应用实例句柄
HWND hWndMain; // MainForm句柄
static HHOOK hKeyHook; // HOOK句柄
static const myMessage=2000; // 自定义消息号
//----------------------------------------------------------------------------------------------------
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_KEYBOARD,(HOOKPROC)HookProc,hInstance,0);
}
else // 卸下HOOK
UnhookWindowsHookEx(hKeyHook);
}
//------------------------------------- ---------------------------------------------------------------
LRESULT CALLBACK HookProc(int nCode,WPARAM wParam,LPARAM lParam)
{ ShowMessage(IntToStr(wParam));
ShowMessage(IntToStr((unsigned int)hWndMain));
PostMessage(hWndMain,myMessage,wParam,lParam);
// 向调用窗体发消息myMessage和虚拟键码(char)(keyMSG->paramL)
return((int)CallNextHookEx(hKeyHook,nCode,wParam,lParam));
}
//----------------------------------------------------------------------------------------------------