Process.Exited并不总是开火

Ale*_*pin 11 c# process

如果我运行以下代码:

Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "notepad.exe";
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new System.EventHandler(Process_OnExit);
myProcess.Start();

public static void Process_OnExit(object sender, EventArgs e)
{
    // Delete the file on exit
}
Run Code Online (Sandbox Code Playgroud)

退出记事本时会引发该事件.如果我尝试相同的代码,但我开始使用图像:

Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = @"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg";
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new System.EventHandler(Process_OnExit);
myProcess.Start();

public static void Process_OnExit(object sender, EventArgs e)
{
    // Delete the file on exit
}
Run Code Online (Sandbox Code Playgroud)

该事件从未被解雇.是因为加载图像的过程永远不会被关闭?

更新:开始的过程并不总是一个图像.它可以是任何东西(pdf,word文档等).也许我的方法不对.用户退出进程后还有其他方法可以删除文件吗?

谢谢

小智 14

您应该为该过程启用事件.

process_name.EnableRaisingEvents = true;
Run Code Online (Sandbox Code Playgroud)

  • 虽然我忘了它在我的代码中,这个答案帮助了我;) (3认同)

Gyu*_*uri 7

我会使用临时文件.有创建临时文件的功能......

我想,由于缺乏过程本身,你的事件没有被解雇.您可以尝试使用shell来"启动"有问题的文档,但没有任何保证会有所有类型文件的处理程序.


小智 5

对于Windows Media Player,请尝试以下代码

 myProcess.StartInfo.FileName = "wmplayer";
 myProcess.StartInfo.Arguments = "yourfilename";
Run Code Online (Sandbox Code Playgroud)

对于Windows图片查看器试试这个

 myProcess.StartInfo.FileName = @"rundll32.exe";
 myProcess.StartInfo.Arguments = @"C:\Windows\System32\shimgvw.dll,ImageView_Fullscreen " + yourfilepath;
Run Code Online (Sandbox Code Playgroud)

现在两者都将在Windows 7中提供您现有的活动