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关闭时,应该触发另一个函数。

有一个简单的方法吗?

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 } 

附加到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(); 

您可以将处理程序附加到Process对象上的Exited事件。 这是关于事件处理程序的MSDN文章的链接 。

您正在寻找的是WaitForExit()函数。

快速谷歌将带您到http://msdn.microsoft.com/en-us/library/ty0d8k56.aspx

或者更好的是其他人都提到过的退出事件;)