WinForm调用bbmod.exe时StandardOutput与StandardError为空的问题
解决WinForm调用bbmod.exe无法捕获输出的问题
1. 修正批处理文件,转发exe输出
当前的批处理可能只是启动exe,但没有将exe的输出传递到自身的标准流中。修改BBMOD_launch.bat内容如下:
@echo off "完整的bbmod.exe路径" %*
替换完整的bbmod.exe路径为实际的exe路径,%*用于传递所有启动参数,确保exe的输出能被批处理的流捕获,这样Process调用bat时就能拿到exe的输出。
2. 调整Process代码,异步捕获输出与错误
原代码仅读取StandardOutput且未处理跨线程问题,容易出现死锁或遗漏错误信息。改用异步读取方式,并处理WinForm控件的跨线程更新:
Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = @"D:\tools\BBMOD\stann_gui\BBMOD_launch.bat"; p.StartInfo.CreateNoWindow = true; // 禁止弹出控制台窗口 // 注册输出接收事件 p.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { // 跨线程更新UI需调用Invoke textBoxLog.Invoke(new Action(() => textBoxLog.Text += e.Data + Environment.NewLine)); } }; // 注册错误接收事件 p.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { textBoxLog.Invoke(new Action(() => textBoxLog.Text += "[错误] " + e.Data + Environment.NewLine)); } }; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit();
3. 直接调用bbmod.exe(跳过批处理)
如果批处理没有额外逻辑,直接调用exe可减少中间层问题:
Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = @"D:\tools\BBMOD\stann_gui\bbmod.exe"; p.StartInfo.CreateNoWindow = true; // 同样注册异步读取事件 p.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { textBoxLog.Invoke(new Action(() => textBoxLog.Text += e.Data + Environment.NewLine)); } }; p.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { textBoxLog.Invoke(new Action(() => textBoxLog.Text += "[错误] " + e.Data + Environment.NewLine)); } }; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit();
4. 处理特殊输出的情况
若bbmod.exe未使用标准输出流(比如直接调用Win32 API写控制台),可通过输出到文件再读取的方式获取内容:
修改批处理文件:
@echo off "完整的bbmod.exe路径" %* > output.log 2>&1
2>&1表示将错误输出重定向到标准输出,统一写入output.log。在Process执行完成后,读取该文件内容并显示:
// 等待进程结束后读取文件 p.WaitForExit(); string output = File.ReadAllText(@"D:\tools\BBMOD\stann_gui\output.log"); textBoxLog.Text = output;
内容的提问来源于stack exchange,提问作者Jack Conradsen
相关产品推荐
相关产品推荐

