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