代码如下




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CreateArticle
{
// 定义委托
public delegate void DelReadStdOutput(string result);
public delegate void DelReadErrOutput(string result);
public partial class Main : Form
{
// 委托事件
public event DelReadStdOutput ReadStdOutput;
public event DelReadErrOutput ReadErrOutput;
public Main()
{
InitializeComponent();
init();
}
public void init()
{
// 异步回显线程委托
ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);
ReadErrOutput += new DelReadErrOutput(ReadErrOutputAction);
}
public Process CmdProcess = null;
private void RealAction(string StartFileName, string StartFileArg)
{
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.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();
}
// 4. 异步调用
private void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
//切换不同线程 上下文操作
this.Invoke(ReadStdOutput, new object[] { e.Data }); //这是wpf需要用dispatcher,如果是winform项目是this.
}
}

private void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
this.Invoke(ReadErrOutput, new object[] { e.Data });
}
}

private void ReadStdOutputAction(string result)
{
Console.WriteLine(result);
}

private void ReadErrOutputAction(string result)
{
Console.WriteLine(result);
}

private void CmdProcess_Exited(object sender, EventArgs e)
{
if (CmdProcess != null) {
CmdProcess.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
RealAction(“ping.exe”, “192.168.1.2 -t”);
}
}
}

说点什么
支持Markdown语法
好耶,沙发还空着ヾ(≧▽≦*)o
Loading...