views:

368

answers:

1

Ok so i know that i have to use setconsolehandler() if i want to manage console closing events.

So i have a little of an understanding, but i don't know how to block the CTRL_CLOSE_EVENT, ive tried returning false/true if it catches that event, but no success

Here is what i have so far (thank you Anton Gogolev!)


[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

public delegate bool HandlerRoutine(CtrlTypes CtrlType);

public enum CtrlTypes{
    CTRL_C_EVENT = 0,
    CTRL_BREAK_EVENT,
    CTRL_CLOSE_EVENT,
    CTRL_LOGOFF_EVENT = 5,
    CTRL_SHUTDOWN_EVENT
}

private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{ 
    if(ctrlType == CtrlTypes.CTRL_CLOSE_EVENT)
        return false;// i have tried true and false and viceversa with the return   
                     // true/false but i cant seem to get it right.
    return true;
}


//and then i use this to call it
SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);

Also is it possible to run a new thread to monitor if the console is closing and block that close if the main thread is in the middle of doing somehting?

+4  A: 

The documentation for SetConsoleCtrlHandler() says:

The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination.

This implies that unlike when handling CTRL+C or CTRL+BREAK events, your process does not get the opportunity to cancel the close, logoff, or shutdown.

Greg Hewgill
So preventing the console from closing via (X) is impossible?
Dacto
@Dacto: yes, it appears that is true. Even if you could prevent that, you could not prevent a user terminating the process from something like Task Manager.
Greg Hewgill
@Greg Hewgill: Yes, that is true, of course if the user really wanted to close it, they could do so via Task Manager, but what if the program is in the middle of downloading a file(at the users request) - closing in the middle of that would only give a partial file.
Dacto