This. openfiledialog. showdialog ();
This.txt filename. Text = This. openfiledialog. filename;
Processstartinfo info = new processstartinfo ();
Info. filename = txtfilename. Text; // external program name
// Set the external program working directory
Info. workingdirectory = txtfilename. Text. tostring (). substring (0, this.txt filename. Text. lastindexof ("\\"));
This. workingdirectory. Text = info. workingdirectory;
Process process;
Try
{
Process = process. Start (Info); // start an external program
}
Catch (win32exception exception)
{
MessageBox. Show ("the system cannot find the specified program file:" + exception. Message );
Return;
Throw;
}
This. starttime. Text = process. starttime. tostring (); // start time of the external program running
Process. waitforexit (3000); // You can wait 3 seconds until the main program closes the external program.
If (process. hasexited = false)
{
This. exittype. Text = "the main program forces the termination of external program running ";
Process. Kill (); // force close an external program
This. endtime. Text = datetime. Now. tostring ();
}
Else
{
This. exittype. Text = "the external program Exits normally ";
This. endtime. Text = process. exittime. tostring (); // exit time after external program execution ends
}
Monitor whether external programs Exit:
Process. enableraisingevents = true;
Process. exited + = new eventhandler (process_exited );
Public void process_exited (Object sender, eventargs E)
{
MessageBox. Show ("external program exited is monitored. ");
}
In addition:
Two methods to monitor whether an external program exits: Take the system notepad as an example.
Method 1: This method blocks the current process until the running external program exits.
System. Diagnostics. Process exep = system. Diagnostics. process. Start (@ "C: \ WINDOWS \ notepad.exe ");
Exep. waitforexit (); // key. It can be executed only after the external program exits.
MessageBox. Show ("notepad.exe finished running ");
Method 2: add an event monitor for an external process. After exiting, get the notification. This method does not block the current process. You can handle other tasks.
System. Diagnostics. Process exep = new system. Diagnostics. Process ();
Exep. startinfo. filename = @ "C: \ WINDOWS \ notepad.exe ";
Exep. enableraisingevents = true;
Exep. exited + = new eventhandler (exep_exited );
Exep. Start ();
// Exep_exited event processing Code. The Code is activated after the external program exits and can be executed.
Void exep_exited (Object sender, eventargs E)
{
MessageBox. Show ("notepad.exe finished running ");
}
Download demo