使用process调用可执行文件或者脚本,程序等。并且异步输出运行过程和结果
![045f0a5889278df2295db256e50a341b.png](https://img-blog.csdnimg.cn/img_convert/045f0a5889278df2295db256e50a341b.png)
--------------------------------划重点------------------------------------------
TextBox:ScrollBars设置为 Vertical
Multiline: Ture
Name: showLog
using System.Diagnostics; //Process创建必须的引用
public delegate void DelReadStdOutput(string result);//定义委托
public event DelReadStdOutput ReadStdOutput;//定义委托事件
ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);//将相应的函数注册到委托事件中
Application.StartupPath //当前执行目录
process_OutputDataReceived :异步调用输出函数
process_ErrorDataReceived:错误输出函数
ScrollToCaret():textbox滚动到最后一行
getSvn_Click:按钮点击事件
public delegate void DelReadStdOutput(string result);//定义委托
Process process;
public event DelReadStdOutput ReadStdOutput;//定义委托事件
public Form1()
{
InitializeComponent();
ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);//将相应的函数注册到委托事件中
}
private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (String.IsNullOrEmpty(e.Data) == false)
{
string str1 = DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "t";
string str2 = str1 + e.Data + "rn";
this.Invoke(ReadStdOutput, new object[] { str2 });//异步调用使用Invoke
}
}
private void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (String.IsNullOrEmpty(e.Data) == false)
{
string str1 = DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "t";
string str2 = str1 + e.Data + "rn";
this.Invoke(ReadStdOutput, new object[] { str2 });//异步调用使用Invoke
}
}
private void ReadStdOutputAction(string result)
{
showLog.AppendText(result);
showLog.ScrollToCaret();
}
private void getSvn_Click(object sender, EventArgs e)
{
this.process = new Process();
this.process.StartInfo.FileName = Application.StartupPath + "xxx.bat ";
//脚本参数 可执行文件如果需要接收参数可通过这个传入 使用空格隔开
//this.process.StartInfo.Arguments = a + " " + b + " " + c + " " + d;
//接收命令行code 例如:ipconfig与cmd中效果相同
//this.process.StartInfo.Arguments = "/k" + code;
//工作目录
this.process.StartInfo.WorkingDirectory = Application.StartupPath;
this.process.StartInfo.UseShellExecute = false;
//接收输入
//this.process.StartInfo.RedirectStandardInput = true;
//输出
this.process.StartInfo.RedirectStandardOutput = true;
//错误
this.process.StartInfo.RedirectStandardError = true;
//创建新的窗口
this.process.StartInfo.CreateNoWindow = true;
this.process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
this.process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
this.process.Start();
showLog.AppendText("Please wait on...rn");
this.process.BeginOutputReadLine();
this.process.BeginErrorReadLine();
this.process.Close();
}