Search This Blog

Sunday, January 11, 2009

How to Handle the ctrl-c or ctrl-break event in c++ application

the next tip tested on windows platform via c++ console application.
sometimes there is a need to handle the ctrl-c or ctrl break event on your console to clean some data or even to release an event, this is the way to do that.
1. create the next function:

BOOL CtrlHandler( DWORD fdwCtrlType )
{
switch( fdwCtrlType )
{
// Handle the CTRL-C and others signal.
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
printf( "Ctrl-C or break event arrived clean my stuff \n\n" );
char buff[200];
CleanMyStuff(buff);
return( FALSE ); // its important to return false to send this event to the next chain
}
return FALSE;
};

return FALSE from this method is important if you want to send this event to the next chain.

2. in your console app in your main function set the next line .

SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) ;

Yaniv

No comments: