private void button1_Click(object sender, EventArgs e)
{
//可执行文件名,例如 D://adb.exe
var exe = label1.Text;
button1.Enabled = false;
//方法1
callProcess(exe, "devices", delegate (String msg)
{
richTextBox1.Text += msg;
});
//方法2
//String res = callProcess(exe, "devices");
//richTextBox1.Text = res;
button1.Enabled = true;
}
///
/// 异步方式 调用可执行exe程序
///
/// exe文件名
/// 传参
/// 调用后返回结果
private void callProcess(string fileName, string Arguments, Action<string> onReceive)
{
var p = new Process();
// 设置属性
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = fileName;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
{
if (String.IsNullOrEmpty(e.Data)) return;
//泛型委托 匿名方法
this.BeginInvoke(onReceive, e.Data);
};
p.StartInfo.Arguments = Arguments;
p.Start();
p.BeginOutputReadLine();
}
///
/// 同步方式 调用可执行exe程序
///
/// exe文件名
/// 传参
/// 返回调用后结果
private string callProcess(string fileName, string arguments)
{
var psi = new ProcessStartInfo(fileName, arguments);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
var pes = Process.Start(psi);
var sbuffer = new StringBuilder();
var sout = pes.StandardOutput;
while (!sout.EndOfStream)
{
var line = sout.ReadLine();
if (String.IsNullOrEmpty(line)) continue;
sbuffer.AppendLine(line);
}
pes.WaitForExit();
pes.Close();
String res = sbuffer.ToString();
sbuffer.Clear();
return res;
}
小提示:
- 若运行报错 StandardOut 未重定向或者该进程尚未启动
- 就加上
RedirectStandardOutput = true;
即可解决