我正在使用C# WPF。
我有使用Start()
命令运行它们的进程列表。
我想知道用户何时退出进程并捕获事件。
我尝试过什么:
myProcess.StartInfo.FileName = fileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
*myProcess 是 Process 对象。
问题出在命令Start()
立即关闭应用程序并调用myProcess_Exited
回调。
我的错误在哪里?
这种行为的唯一原因是,你启动的exe在启动后直接关闭或嘶吼。例如,如果 exe 是一个没有任何用户输入或其他内容的console
应用程序。使用Notepad.exe
尝试您的代码,您会发现它有效。
看看这个IronPython
代码,它主要是 .net 代码作为你的应用程序(只是为了测试目的更容易):
从系统诊断导入过程
def on_exit(s, e):
print ('Exited')
process = Process()
process.StartInfo.FileName = "C:\Windows\System32\notepad.exe"
process.EnableRaisingEvents = True
process.Exited += on_exit;
process.Start()
如果我关闭记事本,则调用退出。
编辑
如果您想检测哪个应用程序已关闭/退出,只需将您的sender
对象Process
并访问它FileName
StartInfo
即可。例如:
private void OnExited(object sender, EventArgs, e)
{
var process = (sender as Process);
Console.WriteLine(process.StartInfo.FileName);
}
希望这有帮助。
myProcess.StartInfo.FileName = fileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
myProcess.WaitForExit();
或
myProcess.WaitForExit(timeout);