Detect console window close (Windows)

Is there a way to detect when the application is closed through closing the console window ?
I am using Chromium Embedded Framework in my application and need to call a function to clear all Chromium resources before closing the application, or else the application just hangs and crash. When closing the sdl window, I get the SDL_QUIT event and I am able to quit the main loop and clean my chromium stuff, but when closing the console window, there is no SDL event dispatched and the app crashes.

I think closing console is very similar to forced close the application. I guess the SIGINT or SIGBREAK is signaled, though I don’t know which of them really happens. The migration guide states that the signal is catched on Unix platforms, guess it’s not on Windows.

Why would you want to uses console on the GUI application, btw?

I tried catching SIGINT etc, but they’re not signaled. I ended up using SetConsoleCtrlHandler, which does the trick, but I wish there was something more clean. We use the console for tracing debug messages, so it is not indispensable, but it sucks that Visual Studio and the debug app hang and eventually makes you have to kill VS and restart it, anytime you close the wrong window :slight_smile:

for anyone insterested :

Code:

#include “Windows.h”

BOOL
WINAPI
ConsoleHandlerRoutine(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_CLOSE_EVENT)
{
//do your stuff
return true;
}
return false;
}

void
main()
{
SetConsoleCtrlHandler(ConsoleHandlerRoutine, true);
}

for anyone insterested :

Code:

#include “Windows.h”

BOOL
WINAPI
ConsoleHandlerRoutine(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_CLOSE_EVENT)
{
//do your stuff
return true;
}
return false;
}

void
main()
{
SetConsoleCtrlHandler(ConsoleHandlerRoutine, true);
}

Be aware that on Windows 7 or later, you have 10 seconds to exit your handler and the process will be kill regardless of whether you return true or false from a CTRL_CLOSE_EVENT