处理kill事件C#

时间:2016-02-08 15:13:40

标签: c# wpf

我正在使用C#WPF 我有使用Start()命令运行它们的进程列表。
我想知道用户何时退出流程并捕获事件 我尝试过的是什么:

myProcess.StartInfo.FileName = fileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();

* myProcess是Process对象。
问题是在Start()命令关闭应用程序并调用myProcess_Exited回调后立即出现问题 我的错误在哪里?

2 个答案:

答案 0 :(得分:6)

这种行为的唯一原因是,你开始的exe是在启动之后直接关闭或直接关闭。例如,如果exe是console应用程序,它没有任何用户输入或其他东西。使用Notepad.exe尝试使用您的代码,您就会发现它有效。

看一下这个IronPython代码,主要是.net代码作为你的应用程序(只是更容易用于测试目的):

来自System.Diagnostics导入过程

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);
}

希望这有帮助。

答案 1 :(得分:-1)

myProcess.StartInfo.FileName = fileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
myProcess.WaitForExit();

或者,

myProcess.WaitForExit(timeout);