Many applications ask user if he really want to close the app by displaying message box with YES (app quits) and NO (app continues to run). Is this possible also for console app (on x icon click or CTRL+C)?
2 Answers
I have never ever gotten the ctrl-c handler to work with this but it may work on your system. This will catch ctrl-break, X or alt-F4. In your program, call SetConsoleCtrlHandler
#define WIN32_LEAN_AND_MEAN #include <windows.h> int main() { SetConsoleCtrlHandler(exit_handler, TRUE); ... } The exit handler is defined as
BOOL WINAPI exit_handler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: // Never gotten this to work - use another method return MessageBox(NULL, "Mr Ctrl C", "Do you wish to exit", MB_YESNO) == IDNO; case CTRL_BREAK_EVENT: return MessageBox(NULL, "Mr Ctrl Break", "Do you wish to exit", MB_YESNO) == IDNO; case CTRL_CLOSE_EVENT: return MessageBox(NULL, "Mr X or Mr Alt-F4", "Do you wish to exit", MB_YESNO) == IDNO; default: return FALSE; } // Never gets here return TRUE; } TRUE means you have handled the command, FALSE means you have not. If you wish to exit, return FALSE.
Edit This works on XP and W7. I haven't tried it on W10 or W8.
1 Comment
Eryk Sun
Closing the console cannot be ignored starting with Windows Vista (NT 6.0). In this case, returning
TRUE for CTRL_CLOSE_EVENT stops processing the handler list and obviously avoids the default handler that calls ExitProcess, like it did in past versions of Windows, but this doesn't matter because csrss.exe terminates the process no more than 5 seconds after it sends the event (i.e. it waits on the injected control thread for 5 seconds).
WM_CLOSE; all applications attached to the console are sent a close event, and they have 5 seconds to exit gracefully before the session server, csrss.exe, terminates them forcefully.