C#检测进程退出
问题描述:
我有以下代码: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
工具IDisposable
,你真的想:
using (System.Diagnostics.Process execute = new System.Diagnostics.Process())
{
execute.StartInfo.FileName = e.FullPath;
execute.Start();
//Process now started, detect exit here
}
答
您可以将处理器的处理对象上已退出的事件。这是事件处理程序的link to the MSDN article。
+4
请注意,它需要'EnableRaisingEvents'设置为true。 – ken2k 2012-02-24 15:03:20
答
附加到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();
答
您正在寻找的是WaitForExit()函数。
快速谷歌将带给你http://msdn.microsoft.com/en-us/library/ty0d8k56.aspx
或者更好的是已退出事件其他人提及;)
根据这个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