C # several methods to start an external program:
1. Start an external program without waiting for it to exit.
2. Start the external program and wait for it to exit.
3. Start an external program and wait for it to exit.
4. Start an external program and monitor its exit through the event. // Using system. diagnostics;
Private string appname = "calc.exe ";
/// <Summary>
/// 1. Start the external program and do not wait for it to exit
/// </Summary>
Private void button#click (Object sender, eventargs E)
{
Process. Start (appname );
MessageBox. Show (string. Format ("external program {0} started! ", This. appname), this. Text,
Messageboxbuttons. OK, messageboxicon. information );
}
/// <Summary>
/// 2. Start the external program and wait for it to exit
/// </Summary>
Private void button2_click (Object sender, eventargs E)
{
Try
{
Process proc = process. Start (appname );
If (Proc! = NULL)
{
Proc. waitforexit (3000 );
If (Proc. hasexited)
MessageBox. Show (string. Format ("external program {0} has exited! ", This. appname), this. Text,
Messageboxbuttons. OK, messageboxicon. information );
Else
{
// Forcibly terminate an external program if it has not ended.
Proc. Kill ();
MessageBox. Show (string. Format ("external program {0} was forcibly terminated! ", This. appname), this. Text,
Messageboxbuttons. OK, messageboxicon. Exclamation );
}
}
}
Catch (argumentexception ex)
{
MessageBox. Show (ex. Message, this. Text,
Messageboxbuttons. OK, messageboxicon. Error );
}
}
/// <Summary>
/// 3. Start the external program and wait for it to exit without limit
/// </Summary>
Private void button3_click (Object sender, eventargs E)
{
Try
{
Process proc = process. Start (appname );
If (Proc! = NULL)
{
Proc. waitforexit ();
MessageBox. Show (string. Format ("external program {0} has exited! ", This. appname), this. Text,
Messageboxbuttons. OK, messageboxicon. information );
}
}
Catch (argumentexception ex)
{
MessageBox. Show (ex. Message, this. Text,
Messageboxbuttons. OK, messageboxicon. Error );
}
}
/// <Summary>
/// 4. Start an external program and monitor its exit through the event
/// </Summary>
Private void button4_click (Object sender, eventargs E)
{
Try
{
// Start an external program
Process proc = process. Start (appname );
If (Proc! = NULL)
{
// The monitoring process exits.
Proc. enableraisingevents = true;
// Specify the exit event Method
Proc. exited + = new eventhandler (proc_exited );
}
}
Catch (argumentexception ex)
{
MessageBox. Show (ex. Message, this. Text,
Messageboxbuttons. OK, messageboxicon. Error );
}
}
/// <Summary>
/// External program exit event
/// </Summary>
Void proc_exited (Object sender, eventargs E)
{
MessageBox. Show (string. Format ("external program {0} has exited! ", This. appname), this. Text,
Messageboxbuttons. OK, messageboxicon. information );
}