views:

36

answers:

2

I'm writting a console application in C++.

I use SetConsoleCtrlHandler to trap close and CTRL+C button. This allows for all my threads to stop and exit properly.

One of the thread performs some saving that require some time to complete and I have some code to wait in the console crtl handle routine. MSDN specify that a box should pop up after 5 seconds for CTRL_CLOSE_EVENT, but instead my process exits.

This is annoying for debugging console application too as the process exits before you can step through and I don't know what may be the problem (I have Windows 7 64bits).

Also, strangely if my routine returns TRUE (to simply disable the close action), it still closes the application. The routine does get called, so the SetConsoleCtrlHandler was successful installed.

e.g.:

BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType)
{
    if (dwCtrlType == CTRL_CLOSE_EVENT)
    {
        return TRUE;
    }

    return FALSE;
}

int _tmain(int argc, _TCHAR* argv[])
{
    BOOL ret = SetConsoleCtrlHandler(ConsoleHandlerRoutine, TRUE);

    while (true)
    {
        Sleep(1000);
    }
    return 0;
}

Any ideas?

A: 

You're making this more complicated than it needs to be. I don't know exactly why your app is closing, but SetConsoleCtrlHandler(NULL, TRUE) should do what you want:

http://msdn.microsoft.com/en-us/library/ms686016(VS.85).aspx

If the HandlerRoutine parameter is NULL, a TRUE value causes the calling process to ignore CTRL+C input, and a FALSE value restores normal processing of CTRL+C input.

Billy ONeal
Still exits when I press the close button on my console. CTRL+C is not the problem as this also does the trick and works: if (dwCtrlType == CTRL_C_EVENT) return TRUE; It's the close button that is causing me problems.
Jeremy
+1  A: 

I suspect that this is by-design on Windows 7 - if the user wants to quit your application, you're not allowed to tell him "No".

Paul Betts
Agreed. The dialog that used to be displayed is gonzo.
Hans Passant