Capture console exit C#

前端 未结 10 2077
悲&欢浪女
悲&欢浪女 2020-11-22 04:01

I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termi

10条回答
  •  感动是毒
    2020-11-22 04:57

    ZeroKelvin's answer works in Windows 10 x64, .NET 4.6 console app. For those who do not need to deal with the CtrlType enum, here is a really simple way to hook into the framework's shutdown:

    class Program
    {
        private delegate bool ConsoleCtrlHandlerDelegate(int sig);
    
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerDelegate handler, bool add);
    
        static ConsoleCtrlHandlerDelegate _consoleCtrlHandler;
    
        static void Main(string[] args)
        {
            _consoleCtrlHandler += s =>
            {
                //DoCustomShutdownStuff();
                return false;   
            };
            SetConsoleCtrlHandler(_consoleCtrlHandler, true);
        }
    }
    

    Returning FALSE from the handler tells the framework that we are not "handling" the control signal, and the next handler function in the list of handlers for this process is used. If none of the handlers returns TRUE, the default handler is called.

    Note that when the user performs a logoff or shutdown, the callback is not called by Windows but is instead terminated immediately.

提交回复
热议问题