我有一个使用异步后台工作程序执行批处理文件的程序。这是代码:
public static void Execute(CmdObj obj, bool batch)
{
CmdObj = obj;
var theWorker = new BackgroundWorker();
theWorker.RunWorkerCompleted += WorkerCompleted;
theWorker.WorkerReportsProgress = true;
if(batch)
{
theWorker.DoWork += WorkerBatchWork;
}else{
theWorker.DoWork += WorkerCommandWork;
}
theWorker.RunWorkerAsync();
}
private static void WorkerBatchWork(object sender, DoWorkEventArgs e)
{
RunBatch(CmdObj);
}
private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
if (temp != null)
ProgramPath = temp.Substring(6);
WriteLog(CmdObj.Activity, false);
WriteLog(CmdObj.Error, true);
CmdObj.TheButton.Enabled = true;
}
private static void RunBatch(CmdObj obj)
{
var process = new Process();
var startInfo = new ProcessStartInfo
{
FileName = obj.SrcFile,
WindowStyle = ProcessWindowStyle.Normal,
CreateNoWindow = false,
RedirectStandardInput = true,
RedirectStandardOutput = false,
RedirectStandardError = true,
UseShellExecute = false
};
try
{
if (!obj.SrcFile.ToLower().Trim().EndsWith(".bat"))
throw new FileLoadException("Not a valid .bat file",obj.SrcFile);
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
//obj.Activity = process.StandardOutput.ReadToEnd();
obj.Error = process.StandardError.ReadToEnd();
}
catch (Exception ex)
{
obj.Exception = ex;
}
finally
{
process.Close();
}
}
class CmdObj
{
public string Command { get; set; }
public string SrcFile { get; set; }
public string Activity { get; set; }
public string Error { get; set; }
public Exception Exception { get; set; }
public Button TheButton { get; set; }
}
所以当我运行这个程序并选择一个批处理文件来执行时,我得到一个空白的 CMD 窗口。当我的程序执行批处理文件时,有什么方法可以在 CMD 窗口中显示输出吗?或者,如果我可以将 CMD 输出发送到文本框或其他控件(实时),那也可以。
谢谢!