C# 进程Process基本的操作说明

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);//将进程的输出信息转移 }

上述代码基本囊括了对进程Process的操作。在C#工具箱中包括进程这一个组件。

posted @ 2014-04-22 16:00  麦田的守望者(0543)  阅读(2373)  评论(0编辑  收藏  举报