Windows控制台应用程序中处理Ctrl+C等
来源:互联网 发布:多用户微商城源码 编辑:程序博客网 时间:2024/05/16 10:29
Just a small code snippet: Let's say you write a console application in native C++ for Windows. Closing the console by pressing Ctrl+C,Ctrl+Break or clicking on close window button [X] kills the process. Is there any way to handle such event and close the program gracefully? Ther answer is calling SetConsoleCtrlHandler() WinAPI function and implementing your own Handler Routine callback function. The template looks like this:
//Handler function will be called on separate thread!
staticBOOL WINAPI console_ctrl_handler(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_C_EVENT: // Ctrl+C
break;
case CTRL_BREAK_EVENT: // Ctrl+Break
break;
case CTRL_CLOSE_EVENT: // Closing the consolewindow
break;
case CTRL_LOGOFF_EVENT: // User logs off. Passed only to services!
break;
case CTRL_SHUTDOWN_EVENT: // System is shutting down. Passed only to services!
break;
}
// Return TRUE if handled this message,further handler functions won't be called.
// Return FALSE to pass this message to further handlers until default handler calls ExitProcess().
return FALSE;
}
int main(int argc, char **argv)
{
SetConsoleCtrlHandler(console_ctrl_handler,TRUE);
...
}
If your program performs some loop and you want the user to be able to break it by closing the console or pressing Ctrl+C, you can solveit this way:
staticvolatile bool g_exit = false;
staticBOOL WINAPI console_ctrl_handler(DWORD dwCtrlType)
{
g_exit = true;
return TRUE;
}
intmain(int argc, char **argv)
{
SetConsoleCtrlHandler(console_ctrl_handler,TRUE);
initialize();
while (!g_exit)
do_a_piece_of_work();
finalize();
}
- Windows控制台应用程序中处理Ctrl+C等
- windows 控制台程序 响应 Ctrl+C
- windows 控制台程序 响应 Ctrl+C
- C# Win32控制台应用程序忽略 Ctrl + C,阻止程序退出
- windows和linux下设置控制台CTRL+C等特殊按键的回调函数之后程序结束的过程
- 控制台程序Ctrl +C 退出
- Linux下利用signal函数处理ctrl+c等信号
- javascript Ctrl +C、Ctrl +V等
- VC MFC 视图中控件响应CTRL+C等消息
- Linux中Ctrl+C、Ctrl+D等按键操作&进程相关命令
- Linux中Ctrl+C、Ctrl+D等按键操作&进程相关命令
- Linux中Ctrl+C、Ctrl+D等按键操作&进程相关命令
- C# 控制台应用程序--随机数
- Ruby控制台应用中的Ctrl+C
- Win32控制台程序,忽略Ctrl+C
- 如何在Java程序中处理Ctrl+C
- 如何在Java程序中处理Ctrl+C
- 如何在Java程序中处理Ctrl+C
- IOS NSURL基本操作
- ios的几种简单有效的数组排序方法
- 最近好累
- 编程新趋势
- jqgrid 按钮事件
- Windows控制台应用程序中处理Ctrl+C等
- 1.Component映射:Object,hbm
- IOS移动端如何获取ArcGIS Server的服务列表
- 敌人的敌人是朋友:苹果欲联手Google干掉Amazon?
- 2.Component映射:工具类
- iphone的mvc结构浅析
- 引用体系_Reference_软引用、弱引用、虚引用
- 有关json的一些理解
- C++ const成员初始化问题