我创建了一个GUI来调用批处理文件,并在单击按钮后在文本框中显示命令行输出。批处理文件运行,输出正确重定向一段时间,直到~80行,文本框输出突然开始显示批处理文件中的实际代码。这是否表示批处理文件中存在错误或我的脚本存在问题?我真的不知道如何开始调试这个问题。
我还注意到我从GUI调用的批处理文件会调用其他批处理文件。这可能会导致问题吗?
我还应该提到批处理文件从命令行成功运行。
private void buildProg_Click(object sender, EventArgs e)
{
using (Process process = new Process())
{
process.StartInfo.WorkingDirectory = some_directory;
process.StartInfo.FileName = "start.bat";
process.StartInfo.Arguments = "arg1 arg2";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.OutputDataReceived += proc_OutputDataReceived;
process.EnableRaisingEvents = true;
process.Start();
process.BeginOutputReadLine();
}
}
private void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.Invoke((Action)(() =>
{
textBox1.AppendText(Environment.NewLine + e.Data);
}));
}
当我从GUI运行它时,批处理文件似乎在这一部分绊倒。
if exist %version_file_path% (
set /p _version= <%version_file_path%
) else (
echo %version_file_path% not found
pause
)
答案 0 :(得分:0)
这里发生了两件事情;
1)/p
语句要求用户输入,暂停命令并等待。
2)你在事件发生之前处理过程,这意味着我们无法模拟继续执行所需的输入。
这几乎解决了它:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
}
Process p;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
p?.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
if (p != null)
p.Dispose();
p = new Process();
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
p.StartInfo.FileName = "test.bat";
p.StartInfo.Arguments = "";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.OutputDataReceived += proc_OutputDataReceived;
p.Start();
p.BeginOutputReadLine();
}
private void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.Invoke((Action)(() =>
{
textBox1.AppendText(Environment.NewLine + e.Data);
}));
//can use either of these lines.
(sender as Process)?.StandardInput.WriteLine();
//p.StandardInput.WriteLine();
}
}