Console Event Handling
http://www.codeproject.com/Articles/2357/Console-Event-Handling
Console Event Handling
Introduction
Everyone programs console applications one time or the other. This programming is more prevalent when people are learning to program, especially while learning the DOS based C/C++ programming. However, when one migrates to Windows programming, console application development takes a back seat. But the Win32 console development holds an important place, especially when the Win32 API contains a good amount of API dedicated to console application development. If you have noticed, even VC++, and latest development technologies like C#, also supports console project development. Console applications are good candidates for testing the core functionality of your Windows application without the unnecessary overhead of a GUI.
But there's always been a sense of helplessness in regard to how to know when certain system related events have occurred, like when user if logging off, or the system is being shutdown, or handling control+break or control+C keyboard events, etc. For a Windows based application, getting to know when such events occur is no problem since they are having a message queue assigned to them that is polled, and assuming that the concerned event is programmed for, it can be handled pretty easily. But this isn't the case with a console application that has no concept of a message queue.
This article intends to discuss how you can handle all kinds of console-based events in any console application. Once you have gone through it, you will see for yourself how trivial this seemingly helpless task is 
Setting Console Traps
The first step in handling console application events is to setup an even trap, technically referred to as installing an event handler. For this purpose, we utilize the SetConsoleCtrlHandler Win32 API that is prototyped as shown below:
BOOL SetConsoleCtrlHandler(
PHANDLER_ROUTINE HandlerRoutine, // handler function
BOOL Add // add or remove handler
);
The HandlerRoutine parameter is a pointer to a function that has the following prototype:
BOOL WINAPI HandlerRoutine(
DWORD dwCtrlType // control signal type
);
All the HandlerRoutine takes is a DWORD parameter that tells what console event has taken place. The parameter can take the following values:
CTRL_C_EVENT- occurs when the user presses CTRL+C, or when it is sent by theGenerateConsoleCtrlEventAPI.CTRL_BREAK_EVENT- occurs when the user presses CTRL+BREAK, or when it is sent by theGenerateConsoleCtrlEventAPI.CTRL_CLOSE_EVENT- occurs when attempt is made to close the console, when the system sends the close signal to all processes associated with a given console.CTRL_LOGOFF_EVENT- occurs when the user is logging off. One cannot determine, however, which user is logging off.CTRL_SHUTDOWN_EVENT- occurs when the system is being shutdown, and is typically sent to services.
Upon receiving the event, the HandlerRoutine can either choose to do some processing, or ignore the event. If the routine chooses not to handle the event, it should return FALSE, and the system shall then proceed to the next installed handler. But incase the routine does handle the event, it should then return TRUE, after doing all the processing it requires. The CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT are typically used to perform any cleanup that is required by the application, and then call the ExitProcess API. Thus, the system has has some timeouts associated with these three events, which is 5 seconds forCTRL_CLOSE_EVENT, and 20 seconds for the other two. If the process doesn't respond within the timeout period, Windows shall then proceed to display the End Task dialog box to the user. If the user proceeds to end the task, then the application will not have any opportunity to perform cleanup. Thus, any cleanup that is required should complete well within the timeout period. Below is an exemplification of the handler routine:
Copy CodeBOOL 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;
}
Now that we have seen how the handler routine works, lets see how to install the handler. To do so, as mentioned earlier in the article, we use the SetConsoleCtrlHandler API as shown below:
if (SetConsoleCtrlHandler(
(PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE)
{
// unable to install handler...
// display message to the user
printf("Unable to install handler!\n");
return -1;
}
The first parameter is a function pointer of the type PHANDLER_ROUTINE, whose prototype has been discussed earlier. The second parameter, if set to TRUE, tries installing the handler, and if set to FALSE, attempts the un-installation. If either attempts are successful, the return value is TRUE. Otherwise FALSE is returned.
So, that's all there is to handling the console application events. After handler is installed, your application will receive the events as and by they come, and when the execution is about to be terminated, the handler maybe un-installed. Pretty easy, eh
?
License
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Share
About the Author

|
Web Developer
|
|
United States ![]() |
I also have various publications to my credit at MSDN Online Peer Journal, Windows Developer Journal (http://www.wdj.com/), Developer 2.0 (http://www.developer2.com/), and PC Quest (http://www.pcquest.com/).
Console Event Handling的更多相关文章
- Event Handling in Spring
Spring内置的event有 1.ContextRefreshedEvent This event is published when the ApplicationContext is eithe ...
- [转]Getting started with SSIS - Part 10: Event Handling and Logging
本文转自:http://beyondrelational.com/modules/12/tutorials/24/tutorials/9686/getting-started-with-ssis-pa ...
- 理解iOS Event Handling
写在前面 最近的一个iOS App项目中遇到了这么问题:通过App访问服务器的大多数资源不需要登录,但是访问某些资源是需要用户提供验证的,一般来说,通常App的做法(譬如美团App)将这些资源放在“我 ...
- Event Handling Guide for iOS--(三)---Event Delivery: The Responder Chain
Event Delivery: The Responder Chain 事件传递:响应链 When you design your app, it’s likely that you want to ...
- Event Handling Guide for iOS--(二)---Gesture Recognizers
Gesture Recognizers 手势识别器 Gesture recognizers convert low-level event handling code into higher-leve ...
- Event Handling Guide for iOS--(一)--About Events in iOS
About Events in iOS Users manipulate their iOS devices in a number of ways, such as touching the scr ...
- UI Framework-1: Aura Event Handling
Event Handling A diagram of the architecture of this system: HWNDMessageHandler owns the WNDPROC ...
- Event Handling Guide for iOS(五)
基本概念: 加速计: 又称加速度计,测量设备运动的加速度. 加速度: 矢量,描绘速度的方向和大小变化的快慢. 陀螺仪: 感测与维持方向的装置. 原文: Motion Event声明: 由于本人水平有限 ...
- [Firebase] 2. Firebase Event Handling
/** * Created by Answer1215 on 11/9/2014. */ var app = angular.module('app', ['firebase']); app.cons ...
随机推荐
- PHP几种抓取网络数据的常见方法
//本小节的名称为 fsockopen,curl与file_get_contents,具体是探讨这三种方式进行网络数据输入输出的一些汇总.关于 fsockopen 前面已经谈了不少,下面开始转入其它. ...
- LNMPA遇到504 Gateway time-out错误的解决方法
Nginx的特点是处理静态很给力,Apache的特点是处理动态很稳定,两者结合起来便是LNMPA,nginx处理前端,apache处理后端,这样处理静态会很快,处理动态会很稳定. 当我以为安装完成以后 ...
- Linux中du和df
Linux运维过程中,常常发现du和df返回值不一样,偶尔会发现区别非常大. 特定情况下,可能df看到磁盘已满,可是du推断磁盘剩余空间非常大. 文件系统分配当中的一些磁盘块用来记录它自身的一些数据. ...
- 【Sprint3冲刺之前】敏捷团队绩效考核(刘铸辉)
TD学生助手团队已经在4.22~4.30完成了为期9天的Sprint2计划,并在Sprint2总结会议中安排了五一放假每个人的任务分配,下面发布下Sprint2冲刺周期的阶段性成果. Sprint2 ...
- kubernetes之故障排查和节点维护(二)
系列目录 案例现场: 测试环境集群本来正常,突然间歇性地出现服务不能正常访问,过一会儿刷新页面又可以正常访问了.进入到服务所在的pod查看输出日志并没有发现异常.使用kubectl get node命 ...
- asyncio协程与并发
并发编程 Python的并发实现有三种方法. 多线程 多进程 协程(生成器) 基本概念 串行:同时只能执行单个任务 并行:同时执行多个任务 在Python中,虽然严格说来多线程与协程都是串行的,但其效 ...
- disabled和readonly
项目中,有一个input控件,input的值需要通过点击一个javascript链接,从弹出的对话框中所列出的项中选择.而不能从input框中直接输入. 刚开始将input的disabled属性设置为 ...
- JDBC编程步奏、问题总结(一)
jdbc编程步骤: 1. 加载数据库驱动 2. 创建并获取数据库链接 3. 创建jdbc statement对象 4. 设置sql语句 5. 设置sql语句中的参数(使用preparedStateme ...
- cookie VS sessionstorge VS localstorge
虽然cookie , localstorge , sessionstorge三者都有存储的功能,但是还是有区别, git上地址:https://github.com/lily1010/cookie-s ...
- ES6 对Math对象的扩展
Math 对象的扩展 Math.trunc() Math.trunc(4.1) // 4 Math.trunc(4.9) // 4 Math.trunc(-4.1) // -4 Math.trunc( ...


