一 控制台程序处理Windows消息
#include <stdio.h>
#include <windows.h>
BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
char mesg[128];
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(int argc, char* argv[])
{
MSG msg;
if (SetConsoleCtrlHandler(
(PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE)
{
printf("Unable to install handler!\n");
return -1;
}
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
首先要安装一个事件钩子,也就是说要建立一个回调函数;ConsoleHandler是回调函数;
然后安装钩子,使用SetConsoleCtrlHandler;
控制台发出了什么消息,有下列值:
CTRL_C_EVENT - 当用户按下了CTRL+C,或者由GenerateConsoleCtrlEvent API发出.
CTRL_BREAK_EVENT - 用户按下CTRL+BREAK, 或者由GenerateConsoleCtrlEvent API发出.
CTRL_CLOSE_EVENT - 当试图关闭控制台程序,系统发送关闭消息。
CTRL_LOGOFF_EVENT - 用户退出时,但是不能决定是哪个用户.
CTRL_SHUTDOWN_EVENT - 当系统被关闭时.
参阅
https://www.cnblogs.com/meihao1989/p/3699050.html
注意要在控制台程序中加入GetMessage、TranslateMessage、DispatchMessage的消息循环才行;
按下Ctrl-C提示;
点窗口关闭按钮提示;
二 控制台处理按键消息
#include <windows.h>
#include <stdio.h>
#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);
}
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;
}
每有键按下释放,都输出如上内容;
这里有个问题;
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是底层键盘钩子,来记录计算机上所有的键盘输入。