我知道如果我想管理控制台关闭事件,我必须使用setconsolehandler(). 我不知道如何阻止CTRL_CLOSE_EVENT.如果它捕获了那个事件,我尝试返回false / true,但没有成功 这是我到目前为止(感谢Anton Go
我不知道如何阻止CTRL_CLOSE_EVENT.如果它捕获了那个事件,我尝试返回false / true,但没有成功
这是我到目前为止(感谢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);
还有可能运行一个新线程来监视控制台是否正在关闭,如果主线程正在做某事,阻止关闭?
SetConsoleCtrlHandler()
的文档说:
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.
这意味着与处理CTRL C或CTRL BREAK事件不同,您的进程无法取消关闭,注销或关闭.