Capture console exit C#

前端 未结 10 1891
悲&欢浪女
悲&欢浪女 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:44

    I am not sure where I found the code on the web, but I found it now in one of my old projects. This will allow you to do cleanup code in your console, e.g. when it is abruptly closed or due to a shutdown...

    [DllImport("Kernel32")]
    private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
    
    private delegate bool EventHandler(CtrlType sig);
    static EventHandler _handler;
    
    enum CtrlType
    {
      CTRL_C_EVENT = 0,
      CTRL_BREAK_EVENT = 1,
      CTRL_CLOSE_EVENT = 2,
      CTRL_LOGOFF_EVENT = 5,
      CTRL_SHUTDOWN_EVENT = 6
    }
    
    private static bool Handler(CtrlType sig)
    {
      switch (sig)
      {
          case CtrlType.CTRL_C_EVENT:
          case CtrlType.CTRL_LOGOFF_EVENT:
          case CtrlType.CTRL_SHUTDOWN_EVENT:
          case CtrlType.CTRL_CLOSE_EVENT:
          default:
              return false;
      }
    }
    
    
    static void Main(string[] args)
    {
      // Some biolerplate to react to close window event
      _handler += new EventHandler(Handler);
      SetConsoleCtrlHandler(_handler, true);
      ...
    }
    

    Update

    For those not checking the comments it seems that this particular solution does not work well (or at all) on Windows 7. The following thread talks about this

提交回复
热议问题