头文件
#include
#include
回调函数
BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
switch(CEvent)
{
case CTRL_C_EVENT:
MessageBox(NULL,"CTRL+C received!","CEvent",MB_OK);
break;
case CTRL_BREAK_EVENT:
MessageBox(NULL,"CTRL+BREAK received!","CEvent",MB_OK);
break;
case CTRL_CLOSE_EVENT:
MessageBox(NULL,"Program being closed!","CEvent",MB_OK);
break;
case CTRL_LOGOFF_EVENT:
MessageBox(NULL,"User is logging off!","CEvent",MB_OK);
break;
case CTRL_SHUTDOWN_EVENT:
MessageBox(NULL,"User is logging off!","CEvent",MB_OK);
break;
}
return TRUE;
}
入口
int main()
{
下钩子
if(SetConsoleCtrlHandler(
(PHANDLER_ROUTINE)ConsoleHander,TRUE) ==0)
{
printf("无法安装处理程序");
return -1;
}
加入消息循环
MSG msg;
while(GetMessage(&msg,0,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
头文件
#include
#incllude
定义
#define WH_KEYBOARD_LL 13
HHOOK g_Hook;
回调
LRESULT CALLBACK KeyboardProc(int code,WPARAM w,LPARAM l)
{
if(w == WM_KEYDOWN)
printf("按下按键\n");
else if(w == WM_KEYUP)
printf("释放按键\n");
return CallNextHookEx(g_Hook,code,w,l);
}
下钩子
SetWindowsHookEx设置键盘钩子;一般第一个参数是WH_KEYBOARD;
但是这里控制台要用WH_KEYBOARD_LL,不然没反应;
WH_KEYBOARD_LL在windows.h里没定义;自己加上#define;
WH_KEYBOARD和WH_KEYBOARD_LL,这两个都是键盘钩子,
MSDN上面说的是WH_KEYBOARD会在应用程序调用GetMessage 或者 PeekMessage函数并且有键盘消息(按下或者释放)的时候会调用相应的函数进行处理,
WH_KEYBOARD_LL这个类型是只要有键盘输入事件的发生,它都会将键盘消息传给相应函数,
WH_KEYBOARD_LL是底层键盘钩子,来记录计算机上所有的键盘输入。
int main()
{
MSG msg;
g_Hook = SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardProc,GetModuleHandle(NULL),0);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(g_Hook);
return 0;
}