I know that I have to use SetConsoleCtrlHandler() if I want to manage console closing events.
I do not know how to block the CTRL_CLOSE_EVENT. I’ve 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 something?
The documentation for
SetConsoleCtrlHandler()says: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.