简体   繁体   English

如何在 C# GUI 表单中运行批处理文件

[英]How to run a batch file within a C# GUI form

How would you execute a batch script within a GUI form in C#如何在 C# 的 GUI 表单中执行批处理脚本

Could anyone provide a sample please?请问有人可以提供样品吗?

This example assumes a Windows Forms application with two text boxes ( RunResults and Errors ).此示例假定 Windows 窗体应用程序具有两个文本框( RunResultsErrors )。

// 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;
        }
    }
}

Updated:更新:

The sample above is a button click event for a button called RunIt .上面的示例是一个名为RunIt的按钮的按钮单击事件。 There's a couple of text boxes on the form, RunResults and Errors where we write the results of stdout and stderr to.表单上有几个文本框, RunResultsErrors ,我们将stdoutstderr的结果写入其中。

I deduce that by executing within a GUI form you mean showing execution results within some UI-Control.我推断通过在 GUI 表单中执行意味着在某些 UI 控件中显示执行结果。

Maybe something like this:也许是这样的:

private void runSyncAndGetResults_Click(object sender, System.EventArgs e)     
{
    System.Diagnostics.ProcessStartInfo psi =
       new System.Diagnostics.ProcessStartInfo(@"C:\batch.bat");

    psi.RedirectStandardOutput = true;
    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    psi.UseShellExecute = false;

    System.Diagnostics.Process batchProcess;
    batchProcess = System.Diagnostics.Process.Start(psi);

    System.IO.StreamReader myOutput = batchProcess.StandardOutput;
    batchProcess.WaitForExit(2000);
    if (batchProcess.HasExited)
    {
        string output = myOutput.ReadToEnd();

        // Print 'output' string to UI-control
    }
}

Example taken from here .示例取自这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM