Wed
28
Sep 2011
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? The answer is calling SetConsoleCtrlHandler() WinAPI function and implementing your own HandlerRoutine callback function. The template looks like this:
// Handler function will be called on separate thread! static BOOL 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 console window 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 solve it this way:
static volatile bool g_exit = false; static BOOL WINAPI console_ctrl_handler(DWORD dwCtrlType) { g_exit = true; return TRUE; } int main(int argc, char **argv) { SetConsoleCtrlHandler(console_ctrl_handler, TRUE); initialize(); while (!g_exit) do_a_piece_of_work(); finalize(); }
Comments | #windows #winapi #c++ Share