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 //