#define WH_KEYBOARD_LL 13
定义一个钩子函数
LRESULT CALLBACK HookFun(int nCode, WPARAM wParam, LPARAM lParam);
HHOOK g_hHook = NULL;
首先要安装钩子
g_hHook = SetWindowsHookEx(WH_KEYBOARD_LL, HookFun, GetModuleHandle(NULL), NULL);
if(g_hHook == NULL)
AfxMessageBox("hook failure!");
在程序结束时要卸载钩子
UnhookWindowsHookEx(g_hHook);
钩子函数的实现
LRESULT CALLBACK HookFun(int nCode, WPARAM wParam, LPARAM lParam)
{
CWPSTRUCT* p = (CWPSTRUCT*) lParam;
if (nCode == HC_ACTION)
{
switch (wParam) //wParam中是消息ID
{
case WM_KEYDOWN:
{
if(p->lParam == 'l' || p->lParam == 'L')
{
// 'l' 键被按下
//do somthing
}
if(p->lParam == VK_ESCAPE)
{//用户按下了Esc
//do somthing
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}