- public int CallPhoneExe(string arg) //arg为进程的命令行参数
- { WaitHandle[] waits =new WaitHandle[2]; //定义两个WaitHandle值,用以控制进程的执行过程
- waits[0] = HSTOP; //AutoResetEvent HSTOP = new AutoResetEvent(false);
- waits[1] = GlobalStop;//AutoResetEvent GlobalStop = new AutoResetEvent(false);
- int iReturn=0;
- Process p = new Process();//新建一个进程
- p.StartInfo.Arguments = arg; //进程的命令行参数
- p.StartInfo.FileName = filepath;//进程启动路径
- p.StartInfo.CreateNoWindow = true;//不显示新进程的窗口
- p.StartInfo.RedirectStandardOutput = true;//输出重定向
- p.StartInfo.RedirectStandardError = true; //Redirect the error ouput!
- p.StartInfo.UseShellExecute = false;
- p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
- p.EnableRaisingEvents = true;
- p.Exited += new EventHandler(p_Exited); //进程自然结束后启动p—Exited事件
- p.OutputDataReceived += new DataReceivedEventHandler(ChangeOutput);//进程有输出时,启动ChangeOutPut函数
- p.Start();//进程启动
- p.BeginOutputReadLine();
- int hstop = WaitHandle.WaitAny(waits);//启动线程暂停,知道WaitHandle中传来有效信号
- switch (hstop)//判断信号是又哪个
- {
- case 0: //进程自然结束
- if (p.WaitForExit(2000))
- iReturn = p.ExitCode; //获取进程的返回值
- else
- {
- CloseProcess();
- iReturn = -2;
- }
- break;
- case 1: //进程被迫结束
- p.Kill();//杀掉进程
- if (!p.HasExited)
- {
- p.Kill();
- }
- iReturn = -3;
- break;
- }
- HSTOP.Reset(); //HSTOP复位,这个变量指示进程自然结束,每次结束后都得自然复位
- p.Close(); //创建的p关闭
- return iReturn;
- }
- private void p_Exited(object sender, EventArgs e)
- {
- HSTOP.Set();
- }
- /输出重定向函数
- private void ChangeOutput(object sendingProcess, DataReceivedEventArgs outLine)
- {
- if (!String.IsNullOrEmpty(outLine.Data)) //字符串不为空时
- MainForm.FireWriteText(outLine.Data,false);//将进程的输出信息转移
- }
总结一下进程的新建和终止的操作过程。代码如下:
最新推荐文章于 2024-05-05 19:37:44 发布
