How to Trap, Ctrl+C, Break, Close events in your console application?

 

imageBy default, the console applications break (stop execution) when user Press, Ctrl+C button, or close by pressing “Close button” in the title bar.

In the post, I’m explaining about how to trap these events in your console application. SetConsoleCtrlHandler function can be used to set the handles for Ctrl+Events.

Function is prototyped as follows.

BOOL WINAPI SetConsoleCtrlHandler(
__in_opt PHANDLER_ROUTINE HandlerRoutine,
__in BOOL Add );

The HandlerRoutine can be a local function in your application and should match with the HandlerRoutine prototype. The Add parameter determines whether the callback to add or removed.

If the HandlerRoutine parameter is NULL, a TRUE value causes the calling process to ignore CTRL+C input, and a FALSE value restores normal processing of CTRL+C input. This attribute of ignoring or processing CTRL+C is inherited by child processes.

If a console process is being debugged and CTRL+C signals have not been disabled, the system generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger, and an application should never use an exception handler to deal with it

More information on this API is detailed in MSDN documentation.

The following describes how to define a control hander routine and how it can be used. In this sample application exits only by pressing “Close” button of the console window.

[sourcecode language='cpp']
#include

using namespace std;

bool gExit = false; // flag to exit from while loop
// Handler callback
BOOL WINAPI TrapCtrlHandler( DWORD dwCtrlType )
{
switch( dwCtrlType )
{
case CTRL_C_EVENT:
cout << "Processing Ctrl+C event\n" << endl ;
break;

case CTRL_CLOSE_EVENT:
cout << "Processing Ctrl+Close event\n" << endl ;
gExit = true; // Set to exit process
break;

case CTRL_BREAK_EVENT:
cout << "Ctrl-Break event" << endl;
break;

default:
return FALSE; // unhandled.Some other in the call back list can process
}
return TRUE; // handled the events
}

void main()
{
if( SetConsoleCtrlHandler( TrapCtrlHandler, TRUE ))
{
cout << "The Control Handler is installed." << endl;
while( !gExit );
}
else
cout << "ERROR: Could not set control handler";
}
[/sourcecode]

 
This entry was posted in Uncategorized. Bookmark the permalink.