32

In C#, I can start a process with

process.start(program.exe);

How do I tell if the program is still running, or if it closed?

Keltari
  • 455
  • 2
  • 5
  • 12

5 Answers5

71

MSDN System.Diagnostics.Process

If you want to know right now, you can check the HasExited property.

var isRunning = !process.HasExited;

If it's a quick process, just wait for it.

process.WaitForExit();

If you're starting one up in the background, subscribe to the Exited event after setting EnableRaisingEvents to true.

process.EnableRaisingEvents = true;
process.Exited += (sender, e) => {  /* do whatever */ };
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
  • This approch doesnt work for ASP.NET, not real asynch run. My web application is blocked while process is running. Any Idea? – Siyon DP May 10 '23 at 08:47
18
Process p = new Process();
p.Exited += new EventHandler(p_Exited);
p.StartInfo.FileName = @"path to file";
p.EnableRaisingEvents = true;
p.Start();

void p_Exited(object sender, EventArgs e)
{
    MessageBox.Show("Process exited");
}
coolmine
  • 4,427
  • 2
  • 33
  • 45
3

Be sure you save the Process object if you use the static Process.Start() call (or create an instance with new), and then either check the HasExited property, or subscribe to the Exited event, depending on your needs.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
1

Assign an event handler to the Exited event.

There is sample code in that MSDN link - I won't repeat it here.

Mike Atlas
  • 8,193
  • 4
  • 46
  • 62
1

Take a look at the MSDN documentation for the Process class.

In particular there is an event (Exited) you can listen to.

Mike Mayer
  • 169
  • 1
  • 8