简体   繁体   中英

C# process.start, how do I know if the process ended?

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?

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 */ };
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");
}

如果使用静态Process.Start()调用(或使用new创建实例),请确保保存Process对象,然后检查HasExited属性,或者根据需要订阅Exited事件。

Assign an event handler to the Exited event.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM