Graceful exit when closing the console window

I am trying to gracefully exit the console application when the close button is pressed.

bool done = false;

BOOL ctrl_handler(DWORD event)
{
    if (event == CTRL_CLOSE_EVENT) {
        done = true;
        return TRUE;
    }
    return FALSE;
}

int main()
{
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)(ctrl_handler), TRUE);

    while (!done)
        do_stuff();

    cleanup();
    cout << "bye";
}

My handler is called correctly, but the main thread does not resume after that, so the buy never happens. If instead I hold CTRL_C_EVENT and press ^ C in the console, then the main thread will continue and exit gracefully. Is there a way to allow the main thread to gracefully exit the console?

I also tried using std :: signal, but this is the same. Works for ^ C, but not for closing a window.

+4
source share
2 answers

Thanks to Jonathan for the tip.

, . , , .

bool done = false;

BOOL ctrl_handler(DWORD event)
{
    if (event == CTRL_CLOSE_EVENT) {
        done = true;
        Sleep(20000); // force exit after 20 seconds
        return TRUE;
    }
    return FALSE;
}

int main()
{
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)(ctrl_handler), TRUE);

    while (!done)
        do_stuff();

    cleanup();
    cout << "bye";
}
+4

, :

if (event == CTRL_CLOSE_EVENT)
{
    ExitThread(0);
//  return TRUE; // warning C4702: unreachable code
}

ExitThread , ctrl_handler. ExitProcess , .

+1

All Articles