加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用SetConsoleHandler()来阻止退出调用

发布时间:2020-12-16 01:29:50 所属栏目:百科 来源:网络整理
导读:我知道如果我想管理控制台关闭事件,我必须使用setconsolehandler(). 我不知道如何阻止CTRL_CLOSE_EVENT.如果它捕获了那个事件,我尝试返回false / true,但没有成功 这是我到目前为止(感谢Anton Gogolev!) [DllImport("Kernel32")]public static extern bool
我知道如果我想管理控制台关闭事件,我必须使用setconsolehandler().

我不知道如何阻止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事件不同,您的进程无法取消关闭,注销或关闭.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读