SystemEvents.SessionEnding does not start until the process terminates (open until)

I try to perform some actions in the program when the user closes the session.

Here is the code:

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

I open the application, it opens notepad. When I close the session:

  • If I did not modify anything in the notebook (so this does not need confirmation when exiting), SO closes the notebook and the SessionEnding event (so in this case it is normal) and Process.Exited later.

  • If I changed something in the notebook, the notebook will ask me if I want to save, and my event will not be fired until the notebook process is closed.

In other words, my program receives a notification only when the process starts. I want my event to be raised in any situation, whether the process is open or not.

Thanks in advance.

+4
source share

Source: https://habr.com/ru/post/1441609/


All Articles