如何运行C#GUI窗体中的批处理文件窗体、批处理文件、GUI

2023-09-03 16:49:42 作者:去讲心中理想

在C#中的GUI表单中你将如何执行批处理脚本

How would you execute a batch script within a GUI form in C#

谁能提供样本吗?

推荐答案

本示例假定Windows窗体应用程序有两个文本框(RunResults 和错误)。

This example assumes a Windows Forms application with two text boxes (RunResults and Errors).

// Remember to also add a using System.Diagnostics at the top of the class
private void RunIt_Click(object sender, EventArgs e)
{
    using (Process p = new Process())
    {
        p.StartInfo.WorkingDirectory = "<path to batch file folder>";
        p.StartInfo.FileName = "<path to batch file itself>";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.Start();
        p.WaitForExit();

        // Capture output from batch file written to stdout and put in the 
        // RunResults textbox
        string output = p.StandardOutput.ReadToEnd();
        if (!String.IsNullOrEmpty(output) && output.Trim() != "")
        {
            this.RunResults.Text = output;
        }

        // Capture any errors written to stderr and put in the errors textbox.
        string errors = p.StandardError.ReadToEnd();
        if (!String.IsNullOrEmpty(errors) & errors.Trim() != ""))
        {
            this.Errors.Text = errors;
        }
    }
}

更新:

样品上面的一个按钮单击事件的一个名为按钮 RunIt 。有形式的一对夫妇的文本框, RunResults 错误在这里我们写的结果标准输出标准错误

The sample above is a button click event for a button called RunIt. There's a couple of text boxes on the form, RunResults and Errors where we write the results of stdout and stderr to.