SystemEvents.SessionEnding在Process(之前打开)关闭之前不会被触发

当用户关闭会话时,我正试图在程序中做一些事情。

这是代码:

using System; using System.Diagnostics; using Microsoft.Win32; using System.Windows.Forms; using System.Threading; public class MyProgram { static Process myProcess = null; public MyProgram() { } // Entry point static void Main(string[] args) { SystemEvents.SessionEnding += SessionEndingEvent; // Does not trigger inmediately, only fires after "myProcess" gets closed/killed myProcess = CreateProcess("notepad.exe", null); myProcess.Exited += pr_Exited; // Invoked at "myProcess" close (works ok) try { myProcess.Start(); } catch (Exception e2) { MessageBox.Show(e2.ToString()); } System.Windows.Forms.Application.Run(); // Aplication loop } static void SessionEndingEvent(object sender, EventArgs e) { MessageBox.Show("Session ending fired!"); } static void pr_Exited(object sender, EventArgs e) { MessageBox.Show("Process Closed"); } static Process CreateProcess(String path, String WorkingDirPath) { Process proceso = new Process(); proceso.StartInfo.FileName = path; proceso.StartInfo.WorkingDirectory = WorkingDirPath; proceso.EnableRaisingEvents = true; return proceso; } } 

我打开我的应用程序,打开一个记事本。 当我关闭会话时:

  • 如果我没有在记事本中修改任何东西(因此它不需要在退出时确认),SO关闭记事本并且会触发SessionEnding事件(因此在这种情况下可以正常)和稍后的Process.Exited。

  • 如果我在记事本中更改了某些内容,记事本会问我是否要保存,并且在记事本进程关闭之前我的事件不会被触发。

换句话说,我的程序仅在我启动的进程未运行时才收到通知。 无论过程是否开放,我都想在任何情况下调用我的事件。

提前致谢。