在应用程序关闭时运行“终止”代码

问题描述:

我有一个运行另一个程序并监视它的程序。在应用程序关闭时运行“终止”代码

static void Main(string[] args) 
{ 
    using (Process exeProc = Process.Start(getStartInfo())) 
    { 
     while (!exeProc.HasExited) 
     { 
      // does some stuff while the monitored program is still running 
     } 
    } 

    // 
    Console.WriteLine("done"); 
} 

当其他程序退出时,我的也一样。

我想反过来也是如此:我如何做到这一点,以便关闭我的程序也将终止我正在监视的过程?

+0

看这个问题:http://stackoverflow.com/questions/4646827/on-exit-for-a-console-application –

已经有另一个问题链接到msdn上的问题,它有一个工作答案(我知道太多间接)。 C# how to receive system close or exit events in a commandline application

我会在这里发布代码,因为它是首选,只是想给出它应该到期的地方,因为我正在逐字逐句地阅读这段代码。

namespace Detect_Console_Application_Exit2 
{ 
    class Program 
    { 
     private static bool isclosing = false; 
     static void Main(string[] args) 
     { 
      SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true); 

      Console.WriteLine("CTRL+C,CTRL+BREAK or suppress the application to exit"); 
      while (!isclosing) ; 

     } 

     private static bool ConsoleCtrlCheck(CtrlTypes ctrlType) 
     { 
      // Put your own handler here 
      switch (ctrlType) 
      { 
       case CtrlTypes.CTRL_C_EVENT: 
        isclosing = true; 
        Console.WriteLine("CTRL+C received!"); 
        break; 

       case CtrlTypes.CTRL_BREAK_EVENT: 
        isclosing = true; 
        Console.WriteLine("CTRL+BREAK received!"); 
        break; 

       case CtrlTypes.CTRL_CLOSE_EVENT: 
        isclosing = true; 
        Console.WriteLine("Program being closed!"); 
        break; 

       case CtrlTypes.CTRL_LOGOFF_EVENT: 
       case CtrlTypes.CTRL_SHUTDOWN_EVENT: 
        isclosing = true; 
        Console.WriteLine("User is logging off!"); 
        break; 

      } 
      return true; 
     } 



     #region unmanaged 
     // Declare the SetConsoleCtrlHandler function 
     // as external and receiving a delegate. 

     [DllImport("Kernel32")] 
     public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add); 

     // A delegate type to be used as the handler routine 
     // for SetConsoleCtrlHandler. 
     public delegate bool HandlerRoutine(CtrlTypes CtrlType); 

     // An enumerated type for the control messages 
     // sent to the handler routine. 
     public enum CtrlTypes 
     { 
      CTRL_C_EVENT = 0, 
      CTRL_BREAK_EVENT, 
      CTRL_CLOSE_EVENT, 
      CTRL_LOGOFF_EVENT = 5, 
      CTRL_SHUTDOWN_EVENT 
     } 

     #endregion 

    } 
} 
+0

哦,我可以很容易地对各种事件的定义不同的行为,以及。这很不错! – MxyL

+0

+1 ...也可以简单地复制,因为该问题在其中一个答案中具有几乎相同的代码... –