2012-02-24 91 views
2

我有以下代碼:C#檢測進程退出

private void fileSystemWatcher_Changed(object sender, System.IO.FileSystemEventArgs e) 
    { 
     System.Diagnostics.Process execute = new System.Diagnostics.Process(); 

     execute.StartInfo.FileName = e.FullPath; 
     execute.Start(); 

     //Process now started, detect exit here 

    } 

的FileSystemWatcher的是看其中的.exe文件越來越保存到一個文件夾。保存到該文件夾​​中的文件被正確執行。但是當打開的exe關閉時,應該觸發另一個函數。

有沒有簡單的方法來做到這一點?

回答

3

Process.WaitForExit

順便一提,因爲Process工具IDisposable,你真的想:

using (System.Diagnostics.Process execute = new System.Diagnostics.Process()) 
{ 
    execute.StartInfo.FileName = e.FullPath; 
    execute.Start(); 

    //Process now started, detect exit here 
} 
+0

根據這個MSDN網頁(http://msdn.microsoft.com/en- us/library/system.diagnostics.process.exited(v = vs.110).aspx),你還需要設置'execute.EnableRaisingEvents = true'以使'execute.WaitForExit()'正常工作。 – 2014-07-28 21:48:20

1

您可以將處理器的處理對象上已退出的事件。這是事件處理程序的link to the MSDN article

+4

請注意,它需要'EnableRaisingEvents'設置爲true。 – ken2k 2012-02-24 15:03:20

15

附加到Process.Exited事件。示例:

System.Diagnostics.Process execute = new System.Diagnostics.Process();  
execute.StartInfo.FileName = e.FullPath;  
execute.EnableRaisingEvents = true; 

execute.Exited += (sender, e) => { 
    Debug.WriteLine("Process exited with exit code " + execute.ExitCode.ToString()); 
} 

execute.Start();