如何使用SetConsoleHandler()来阻止退出调用 [英] How to use SetConsoleHandler() to block exit calls
问题描述
我知道如果我想要管理控制台关闭事件,我必须使用 setconsolehandler()
。
I know that I have to use setconsolehandler()
if I want to manage console closing events.
我不知道如何阻止 CTRL_CLOSE_EVENT
。我尝试返回false / true,如果它捕获该事件,但没有成功
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
这是我到目前为止(谢谢Anton Gogolev!)
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);
也可以运行一个新的线程来监视,如果控制台关闭并阻止关闭if主线程正在做某事?
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?
推荐答案
当用户关闭控制台,注销或关闭系统时,系统会生成CTRL_CLOSE_EVENT,CTRL_LOGOFF_EVENT和CTRL_SHUTDOWN_EVENT信号,
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事件不同,您的进程不会有机会取消关闭,注销或关闭。
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.
这篇关于如何使用SetConsoleHandler()来阻止退出调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!