【发布时间】:2020-11-05 06:06:12
【问题描述】:
所有, 我正在尝试通过 C# winforms 应用程序执行一系列批处理文件。在这个早期阶段,使用测试批处理文件,除非我设置 UseShellExecute = true,否则我无法让流程执行遵守批处理文件中的超时,这是我试图避免的事情。我的目标是执行脚本文件并将输出重定向到 GUI,如下面的代码所示:
Process process;
public void ExecuteScript(string workingDirectory, string batchFileName)
{
if (process != null)
process.Dispose();
process = new Process();
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.FileName = workingDirectory + batchFileName;
process.StartInfo.Arguments = "";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.EnableRaisingEvents = true;
process.OutputDataReceived += proc_OutputDataReceived;
process.Start();
process.BeginOutputReadLine();
process.Exited += OnProcessExit;
}
private void OnProcessExit(object sender, EventArgs e)
{
Console.WriteLine("the script has ended");
}
private void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.Invoke((Action)(() =>
{
textBox1.AppendText(Environment.NewLine + e.Data);
}));
(sender as Process)?.StandardInput.WriteLine();
}
我的批处理文件如下所示:
@echo off
echo This is a running script
timeout /t 10
echo Done sleeping. Will Exit
exit
我可以调用适当的设置组合来防止命令窗口出现,同时仍然重定向输出并正确执行脚本吗?
【问题讨论】:
标签: c# winforms batch-file process