Why is the destructor not called when I click the close button on the console?
I have a command line application on Windows 7. It basically consists of an endless loop. When I click the close command window button, it seems to be killed instantly. However, I am closing the SQLite database connection in the destructor, so I'm afraid the database might get corrupted. Even if it doesn't, I would like to be able to finish my object correctly (maybe write something to a file, do a registration, etc.).
Is there some way to make sure my destructor is called? What exactly happens if I close the window? Is there a softer way to close the program?
source to share
The console app does not have a message loop that asks you to exit, but Windows gives you the option to register a function to receive some notifications you might need. One of them is the closing notification.
First of all, declare a function that Windows will call for this purpose with the prototype specified by HandlerRoutine :
BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType) {
if (CTRL_CLOSE_EVENT == dwCtrlType) {
return TRUE;
}
return FALSE;
}
Now register this function using SetControlCtrlHandler before you start the loop:
int main(int argc, char* argv[])
{
if (FALSE == SetConsoleCtrlHandler(ConsoleHandlerRoutine, TRUE)) {
// Cannot register your handler? Check GetLastError()
}
while (true)
{
// This is your loop
}
return 0;
}
It's done. You can explicitly delete the objects you want to delete, or you can simply set a flag that breaks your infinite loop.
Note that you will get more events (Windows shutdown CTRL_SHUTDOWN_EVENT
, user logout CTRL_LOGOFF_EVENT
, user disconnect CTRL_C_EVENT
, shutdown CTRL_CLOSE_EVENT
)), handle what you need / want.
source to share