http://www.codeproject.com/Articles/2357/Console-Event-Handling

Console Event Handling

Kumar Gaurav Khanna, 29 May 2002

   4.59 (46 votes)
 
Rate this:  
 
This article discusses how to handle console-window specific events

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:

Hide   Copy Code
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:

Hide   Copy Code
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 theGenerateConsoleCtrlEvent API.
  • CTRL_BREAK_EVENT - occurs when the user presses CTRL+BREAK, or when it is sent by theGenerateConsoleCtrlEvent API.
  • 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_EVENTCTRL_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:

Hide   Shrink    Copy Code
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;
}

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:

Hide   Copy Code
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

Kumar Gaurav Khanna

 
Web Developer
United States 
I hold Early Acheiver in MCSE 2000, MCSE NT 4.0, MCP+I, and actively involved in programming using C/C++, .NET framework, C#, Win32 API, VB, ASP and MFC.

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的更多相关文章

  1. Event Handling in Spring

    Spring内置的event有 1.ContextRefreshedEvent This event is published when the ApplicationContext is eithe ...

  2. [转]Getting started with SSIS - Part 10: Event Handling and Logging

    本文转自:http://beyondrelational.com/modules/12/tutorials/24/tutorials/9686/getting-started-with-ssis-pa ...

  3. 理解iOS Event Handling

    写在前面 最近的一个iOS App项目中遇到了这么问题:通过App访问服务器的大多数资源不需要登录,但是访问某些资源是需要用户提供验证的,一般来说,通常App的做法(譬如美团App)将这些资源放在“我 ...

  4. 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 ...

  5. Event Handling Guide for iOS--(二)---Gesture Recognizers

    Gesture Recognizers 手势识别器 Gesture recognizers convert low-level event handling code into higher-leve ...

  6. 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 ...

  7. UI Framework-1: Aura Event Handling

    Event Handling A diagram of the architecture of this system:     HWNDMessageHandler owns the WNDPROC ...

  8. Event Handling Guide for iOS(五)

    基本概念: 加速计: 又称加速度计,测量设备运动的加速度. 加速度: 矢量,描绘速度的方向和大小变化的快慢. 陀螺仪: 感测与维持方向的装置. 原文: Motion Event声明: 由于本人水平有限 ...

  9. [Firebase] 2. Firebase Event Handling

    /** * Created by Answer1215 on 11/9/2014. */ var app = angular.module('app', ['firebase']); app.cons ...

随机推荐

  1. ffmpeg H264 编解码配置

    ffmpeg H264编解码前面有文章介绍下,本文主要介绍一些参数配置. 编码: int InitEncoderCodec( int iWidth, int iHeight) { AVCodec * ...

  2. java 是 传值还是传址 Pass-by-value or Pass-by-reference

    原文在此,写的非常好,解答了我的疑问 http://www.javadude.com/articles/passbyvalue.htm 首先放上一段代码,我是在找寻这段代码的内部原理的时候,在stac ...

  3. Java 语法清单

      Java 语法清单 Java 语法清单翻译自 egek92 的 JavaCheatSheet,从属于笔者的 Java 入门与实践系列.时间仓促,笔者只是简单翻译了些标题与内容整理,支持原作者请前往 ...

  4. MySQL 存储过程 (3)

    以下介绍下像数据库循环插入数据操作 第一步:建立存储过程用到的信息表

  5. 获取一组radio按钮选中的值Value

    1.效果 2.HTML代码 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind=" ...

  6. VCL里的构造函数

    好奇,为什么Create函数明明是个构造函数,还要带上override;这是C++里没有的事情.我虽然也明白其大致的作用和目的,但还是没有见到官方和权威的说法.如果哪位大大见到此文,还望给一个详细一点 ...

  7. 【WordSearch】Word Search

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  8. AndroidPageObjectTest_Simple.java

    以下代码使用ApiDemos-debug.apk进行测试 //这个脚本用于演示PageFactory的功能:使用注解@FindBy.@AndroidFindBy.@IOSFindBy定位元素.注解用法 ...

  9. 剑指Offer:重建二叉树【7】

    剑指Offer:重建二叉树[7] 题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5 ...

  10. Linux系统上安装字体

    最近项目中需要控制字体类型,然后就上网查了一下在linux系统上安装字体,在window上和linux上,字体要求一样,都是ttf格式,下面这是window上的字体截图 在linux系统中的/usr/ ...