Just a small code snippet: Let's say you write a console application in native C++ for Windows. Closing the console by pressing Ctrl+C,Ctrl+Break or clicking on close window button [X] kills the process. Is there any way to handle such event and close the program gracefully? Ther answer is calling SetConsoleCtrlHandler() WinAPI function and implementing your own Handler Routine callback function. The template looks like this:
//Handler function will be called on separate thread!
staticBOOL WINAPI console_ctrl_handler(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_C_EVENT: // Ctrl+C
break;
case CTRL_BREAK_EVENT: // Ctrl+Break
break;
case CTRL_CLOSE_EVENT: // Closing the consolewindow
break;
case CTRL_LOGOFF_EVENT: // User logs off. Passed only to services!
break;
case CTRL_SHUTDOWN_EVENT: // System is shutting down. Passed only to services!
break;
}
// Return TRUE if handled this message,further handler functions won't be called.
// Return FALSE to pass this message to further handlers until default handler calls ExitProcess().
return FALSE;
}
int main(int argc, char **argv)
{
SetConsoleCtrlHandler(console_ctrl_handler,TRUE);
...
}
If your program performs some loop and you want the user to be able to break it by closing the console or pressing Ctrl+C, you can solveit this way:
staticvolatile bool g_exit = false;
staticBOOL WINAPI console_ctrl_handler(DWORD dwCtrlType)
{
g_exit = true;
return TRUE;
}
intmain(int argc, char **argv)
{
SetConsoleCtrlHandler(console_ctrl_handler,TRUE);
initialize();
while (!g_exit)
do_a_piece_of_work();
finalize();
}