2017-09-28 38 views
0

在我的表单中,我通过运行一个可执行文件loader.exe(Visual Studio中的另一个项目)开始工作,该文件随时间在控制台上打印一些信息,直到它终止。我想要做的是: 我想在阅读控制台的同时继续执行,并在我的表单应用程序的文本框textBoxConsole1中显示最新输出(带有一些额外信息的百分比),以便用户可以了解进度。读取过程输出[已更新]

编辑:目前,它有点复杂。它显示一些输出,然后显示额外的输出,然后显示整个剩余的输出。与loader.exe不一样。

在这个线程 C# Show output of Process in real time

Mr.Passant说:

“这是非常正常的,过程中会切换到时您重定向它的输出缓冲输出如果不吐一个。很多文字,那么缓冲区不会填满足够导致它被刷新。如果你不能修复程序的代码,你无能为力。

那么这个“足够”到底有多少?我的代码:

private void buttonConnect_Click(object sender, EventArgs e) 
    { 
     Thread findThread = new Thread(findProcedure); 
     findThread.Start(); 
    } 

    public void findProcedure() 
    { 
     Process process = new Process(); 
     process.StartInfo.FileName = PATH; 
     process.StartInfo.UseShellExecute = false; 
     process.StartInfo.RedirectStandardOutput = true; 
     process.StartInfo.RedirectStandardError = true; 
     process.StartInfo.RedirectStandardInput = true; 
     process.StartInfo.CreateNoWindow = true; 

     process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => 
     { 
      if (!String.IsNullOrEmpty(e.Data)) 
      { 
       //textBoxConsole1.Text = e.Data; //Cross-thread validation exception 
       //use thread safe set method instead 
       setConsole1(e.Data); 
      } 
     }); 


     process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => 
     { 
      if (!String.IsNullOrEmpty(e.Data)) 
      { 
       setConsole3(e.Data); 
      } 
     }); 

     process.Start(); 
     process.BeginOutputReadLine(); 
     process.BeginErrorReadLine(); 

     process.WaitForExit(); 
    } 

而我的线程安全的设置方法:

public void setConsole1(string str) 
    { 
     if (this.textBoxConsole1.InvokeRequired) 
     { 
      SetTextCallback d = new SetTextCallback(setConsole1); 
      this.Invoke(d, new object[] { str }); 
     } 
     else 
     { 
      textBoxConsole1.AppendText(str); 
      textBoxConsole1.AppendText(Environment.NewLine); 
     } 
    } 

错误的数据处理方法setConsole3相同setConsole1,但套到另一个箱子。

+0

你好,欢迎来到SO,我们可以分享一些代码,然后我们都可以看到它是如何工作的,哪些可能是错误的?你得到一个错误或什么? 请参阅[如何提问](https://stackoverflow.com/help/how-to-ask)页面以获得澄清此问题的帮助。 – rmjoia

+0

看看:[https://stackoverflow.com/questions/285760/how-to-spawn-a-process-and-capture-its-stdout-in-net](https://stackoverflow.com/问题/ 285760 /怎样生成一个进程并捕获它的stdout-in-net) – corners

+0

@corners当生成它的进程终止但问题是我想捕获它时该过程使用它,以便我可以看到我的表单上的进度 –

回答

0

您应该在StartInfo中将RedirectStandardOutput设置为true。

Process process = new Process(); 
try 
{ 
    process.StartInfo.FileName = fileName // Loader.exe in this case; 
    ... 
    //other startInfo props 
    ... 
    process.StartInfo.RedirectStandardError = true; 
    process.StartInfo.RedirectStandardOutput = true; 
    process.OutputDataReceived += OutputReceivedHandler //OR (sender, e) => Console.WriteLine(e.Data); 
    process.ErrorDataReceived += ErrorReceivedHandler; 
    process.Start(); 
    process.BeginOutputReadline(); 
    process.BeginErrorReadLine(); 
    .... 
    //other thing such as wait for exit 
}