Summarize the process of creating and terminating a process. Check the Code:
Public int callphoneexe (string Arg) // Arg is the process's command line parameter <br/> {waithandle [] waits = new waithandle [2]; // defines two waithandle values, used to control the execution process of a process <br/> waits [0] = hstop; // autoresetevent hstop = new autoresetevent (false); <br/> waits [1] = globalstop; // autoresetevent globalstop = new autoresetevent (false); <br/> int ireturn = 0; <br/> PROCESS p = new process (); // create a process <br/> P. startinfo. arguments = ARG; // command line parameter of the Process <br/> P. startinfo. filename = filepath; // process startup path </P> <p> P. startinfo. createnowindow = true; // the window of the new process is not displayed <br/> P. startinfo. redirectstandardoutput = true; // output redirection <br/> P. startinfo. redirectstandarderror = true; // redirect the error ouput! <Br/> P. startinfo. useshellexecute = false; <br/> P. startinfo. windowstyle = system. diagnostics. processwindowstyle. hidden; </P> <p> P. enableraisingevents = true; <br/> P. exited + = new eventhandler (p_exited); // start the p-exited event after the process ends naturally. <br/> P. outputdatareceived + = new datareceivedeventhandler (changeoutput); // when the process has output, start the changeoutput function </P> <p> P. start (); // process startup <br/> P. beginoutputreadline (); </P> <p> int hstop = Waithandle. waitany (waits); // The start thread is paused and the valid signal in waithandle is known. <br/> switch (hstop) // determine the signal <br/> {<br/> case 0: // The process ends naturally. <br/> If (P. waitforexit (2000) <br/> ireturn = P. exitcode; // obtain the returned value of a process <br/> else <br/> {<br/> closeprocess (); <br/> ireturn =-2; <br/>}< br/> break; <br/> case 1: // The process is forced to end. <br/> P. kill (); // kill the Process <br/> If (! P. hasexited) <br/>{< br/> P. kill (); <br/>}< br/> ireturn =-3; <br/> break; <br/>}< br/> hstop. reset (); // hstop reset. This variable indicates that the process ends naturally and must be reset after each end. <br/> P. close (); // close the created P <br/> return ireturn; <br/>}</P> <p> private void p_exited (Object sender, eventargs E) <br/>{< br/> hstop. set (); <br/>}</P> <p> // output redirection function <br/> private void changeoutput (Object sendingprocess, datareceivedeventargs outline) <br/> {<B R/> If (! String. isnullorempty (outline. data) // when the string is not empty <br/> mainform. firewritetext (outline. data, false); // transfer process output information <br/>}
The steps for creating a process are summarized above. To terminate a process, you can set a valid signal for the globalstop variable in the main thread to call P. Kill ()
Find the method of the specified process in all processes of the system:
Foreach (PROCESS p in process. getprocesses ())
{
If (P. processname = "specialprocess ")
{
// Do smth
}
}