2011-05-14 20 views

回答

4

本示例假定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; 
     } 
    } 
} 

更新時間:

樣品上方是一個名爲RunIt按鈕一個按鈕單擊事件。表單上有幾個文本框,RunResultsErrors,其中我們將stdoutstderr的結果寫入。

+0

@Kev嗨,謝謝,這將如何初始化,但例如在一個文本框? – Mike 2011-05-14 22:25:30

+0

@Mike - 我已經更新了我的答案,那是什麼意思? – Kev 2011-05-14 22:35:46

+0

@Kev,嗨,是的,這是感謝你,我做了它的書面,雖然我得到一些編譯錯誤,我認爲這可能是因爲我使用NET框架3.5/VS 2008(將嘗試升級..), – Mike 2011-05-14 23:04:59

5

System.Diagnotics.Process.Start(「yourbatch.bat」);應該這樣做。

Another thread covering the same issue

+0

@ Will A您好,感謝您的及時回覆,但您將如何將其實施到表單中? – Mike 2011-05-14 22:09:46

+0

@Mike - 完全按照書面形式,邁克 - 或者你真的想運行批處理文件,並在窗體的UI中顯示輸出? – 2011-05-14 22:10:39

+0

@Will A是的我希望UI上的輸出顯示在 – Mike 2011-05-14 22:12:07

1

我推斷出在GUI窗體中執行你的意思是在一些UI控件中顯示執行結果。

也許是這樣的:

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

來自實例here拍攝。

+0

你將如何從一個按鈕調用這個函數? – Mike 2011-05-14 22:31:09