See another application, and if it closes my application (without polling) C #

hi I want to β€œplug in” another application, so when it closes, I can close my application.

I do not want to interrogate the current process, as it seems unnecessarily intense if I want to respond in real time.

I believe that applications send a message in windows when they are created or closed, etc. How can I tie this to find out when it closes?

for example, it allows me to say that my application downloads checks of running processes to ensure that the notebook is loaded, and if it remains loaded until the notebook is closed. since notepad is closed by my application, as it is known and exits ...

Is it possible, if so, how?

he needs to work with xp vista and win7

+3
source share
2 answers

If you have a Process instance for the running application, you can use Process.WaitForExit, which will block until the process is closed. Of course, you can put WaitForExit in another thread so that your main thread does not block.

Here is an example without using a separate thread

Process[] processes = Process.GetProcessesByName("notepad");
if (processes.Length > 0)
{
  processes[0].WaitForExit();
}

Here is a simple version that uses a thread to track the process.

public static class ProcessMonitor
{
  public static event EventHandler ProcessClosed;

  public static void MonitorForExit(Process process)
  {
    Thread thread = new Thread(() =>
    {
      process.WaitForExit();
      OnProcessClosed(EventArgs.Empty);
    });
    thread.Start();      
  }

  private static void OnProcessClosed(EventArgs e)
  {
    if (ProcessClosed != null)
    {
      ProcessClosed(null, e);
    }
  }
}

- , . WPF WinForms, , , . stackoverflow, , WinForms WPF , UI.

static void Main(string[] args)
{
  // Wire up the event handler for the ProcessClosed event
  ProcessMonitor.ProcessClosed += new EventHandler((s,e) =>
  {
    Console.WriteLine("Process Closed");
  });

  Process[] processes = Process.GetProcessesByName("notepad");
  if (processes.Length > 0)
  {
    ProcessMonitor.MonitorForExit(processes[0]);
  }
  else
  {
    Console.WriteLine("Process not running");        
  }
  Console.ReadKey(true);
}
+9

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


All Articles