2013-12-14 86 views
1

我有一個運行另一個程序並監視它的程序。在應用程序關閉時運行「終止」代碼

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 –

回答

1

已經有另一個問題鏈接到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 ...也可以簡單地複製,因爲該問題在其中一個答案中具有幾乎相同的代碼... –

相關問題