同步打开命令提示符并在文本框中显示输出

问题描述:

即时尝试几天来实时“捕获”命令提示符的输出,目前为止我所做的最好的事情是以下内容,它同步启动cmd并异步输出的阅读(我无法想出任何其他方式来实时完成)。事情是,应用程序中的命令继续像平常一样,而不是等待cmd上的进程完成。即在cmd完成其操作之前弹出消息框。感谢您的每一个回答:)同步打开命令提示符并在文本框中显示输出

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Forms; 
using System.IO; 
using System.Diagnostics; 
using System.Threading; 

namespace WindowsFormsApplication3 
{ 
    public partial class Form1 : Form 
    { 
     public bool progressbool = false; 
     public string strOutput; 
     public string pathforit = Directory.GetCurrentDirectory(); 
     public string line; 
     System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); 

    public Form1() 
    { 
     InitializeComponent(); 
     commandline(); 


    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    public void commandline() 
    { 

     pProcess.StartInfo.FileName = "cmd.exe"; 
     pProcess.StartInfo.UseShellExecute = false; 
     pProcess.StartInfo.RedirectStandardInput = true; 
     pProcess.StartInfo.RedirectStandardOutput = true; 
     pProcess.StartInfo.CreateNoWindow = true; 
     pProcess.Exited += new EventHandler(myProcess_Exited); 
     pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived); 
     pProcess.Start(); 
     pProcess.BeginOutputReadLine(); 
     pProcess.StandardInput.WriteLine("dir"); 


    } 


    void process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) 
    { 
     this.AddText(e.Data); 
    } 
    delegate void AddTextCallback(string text); 
    private void AddText(string text) 
    { 
     if (this.textBox1.InvokeRequired) 
     { 
      AddTextCallback d = new AddTextCallback(AddText); 
      this.Invoke(d, new object[] { text }); 
     } 
     else 
     { 
      this.textBox1.Text += text + Environment.NewLine; 
      textBox1.SelectionStart = textBox1.Text.Length; 
      textBox1.ScrollToCaret(); 
      textBox1.Refresh(); 
     } 
    } 
    private void myProcess_Exited(object sender, System.EventArgs e) 
    { 

     MessageBox.Show("The commands Operations have finished"); 
    } 
} 

你可以通过调用WaitForExit来做到这一点。
但是,不要这样做;它会在你等待的时候冻结你的程序。
你不应该在UI线程上执行阻塞操作。

取而代之的是,处理Exited事件并在那里显示消息框。

+0

+1暗示的东西,你告诉他不要做。 :) – Nathan

+0

感谢您的答案,我真的很感激它。我编辑了上面的代码以显示它现在是怎么回事,问题是如果我运行该程序,该过程永远不会结束,因此不会得到消息框 – Stefanou

+0

@Stefanou:除非执行'exit',否则'cmd'永远不会退出。 – SLaks

试图钩住进程已退出事件,并把你的消息框在

pProcess.Exited += // my exit handler