以下的代碼為new Process() 調用cmd命令,並將結果異步回顯到Form的例子:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Diagnostics;
- namespace CmdCallbackShow
- {
- // 1.定義委托
- public delegate void DelReadStdOutput(string result);
- public delegate void DelReadErrOutput(string result);
- public partial class Form1 : Form
- {
- // 2.定義委托事件
- public event DelReadStdOutput ReadStdOutput;
- public event DelReadErrOutput ReadErrOutput;
- public Form1()
- {
- InitializeComponent();
- Init();
- }
- private void Init()
- {
- //3.將相應函數注冊到委托事件中
- ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);
- ReadErrOutput += new DelReadErrOutput(ReadErrOutputAction);
- }
- private void button1_Click(object sender, EventArgs e)
- {
- // 啟動進程執行相應命令,此例中以執行ping.exe為例
- RealAction("ping.exe", textBox1.Text);
- }
- private void RealAction(string StartFileName, string StartFileArg)
- {
- Process CmdProcess = new Process();
- CmdProcess.StartInfo.FileName = StartFileName; // 命令
- CmdProcess.StartInfo.Arguments = StartFileArg; // 參數
- CmdProcess.StartInfo.CreateNoWindow = true; // 不創建新窗口
- CmdProcess.StartInfo.UseShellExecute = false;
- CmdProcess.StartInfo.RedirectStandardInput = true; // 重定向輸入
- CmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向標准輸出
- CmdProcess.StartInfo.RedirectStandardError = true; // 重定向錯誤輸出
- //CmdProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
- CmdProcess.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
- CmdProcess.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
- CmdProcess.EnableRaisingEvents = true; // 啟用Exited事件
- CmdProcess.Exited += new EventHandler(CmdProcess_Exited); // 注冊進程結束事件
- CmdProcess.Start();
- CmdProcess.BeginOutputReadLine();
- CmdProcess.BeginErrorReadLine();
- // 如果打開注釋,則以同步方式執行命令,此例子中用Exited事件異步執行。
- // CmdProcess.WaitForExit();
- }
- private void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
- {
- if (e.Data != null)
- {
- // 4. 異步調用,需要invoke
- this.Invoke(ReadStdOutput, new object[] { e.Data });
- }
- }
- private void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
- {
- if (e.Data != null)
- {
- this.Invoke(ReadErrOutput, new object[] { e.Data });
- }
- }
- private void ReadStdOutputAction(string result)
- {
- this.textBoxShowStdRet.AppendText(result + "\r\n");
- }
- private void ReadErrOutputAction(string result)
- {
- this.textBoxShowErrRet.AppendText(result + "\r\n");
- }
- private void CmdProcess_Exited(object sender, EventArgs e)
- {
- // 執行結束后觸發
- }
- }
- }