0

I have a executable called background.exe which contains a c program which generates some output to the console window when executed using command prompt.

But now I want to show the output of the background.exe in c# winform application textbox. I created a cmd process and called the background.exe but it does not display output created by the c program in the textbox. If I input commands like "Dir" then output is displayed. Please help.

      Process cmdProcess;
      StreamWriter cmdStreamWriter;

      cmdOutput = new StringBuilder("");
      cmdProcess = new Process();


      cmdProcess.StartInfo.FileName = "cmd.exe";
      cmdProcess.StartInfo.UseShellExecute = false;
      cmdProcess.StartInfo.CreateNoWindow = true;
      cmdProcess.StartInfo.RedirectStandardOutput = true;

      cmdProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
      cmdProcess.StartInfo.RedirectStandardInput = true;
      cmdProcess.Start();


      cmdStreamWriter = cmdProcess.StandardInput;

      cmdProcess.BeginOutputReadLine();


      cmdStreamWriter.WriteLine("start background.exe");


  }

  delegate void SetTextCallback(string text);

  private void SetText(string text)
  {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (this.textBox1.InvokeRequired)
      {
          SetTextCallback d = new SetTextCallback(SetText);
          this.Invoke(d, new object[] { text });
      }
      else
      {
          this.textBox1.Text = text;
      }
  }

  private  void SortOutputHandler(object sendingProcess,
        DataReceivedEventArgs outLine)
    {
        if (!String.IsNullOrEmpty(outLine.Data))
        {
            cmdOutput.Append(Environment.NewLine + outLine.Data);
            SetText(cmdOutput.ToString());

        }
    }
Dinesh wakti
  • 121
  • 2
  • 8

1 Answers1

0

Your program is basically correct. dir causes cmd.exe to print output, which your program captures. start causes cmd.exe to open a process with a new console, with the output not wired into cmd.exe for it then to relay to your program. Those are material differences. Don't use start, and you should have more luck. Also be sure to flush frequently in background.exe in case you have more problems. Finally I don't understand any of your crazy code for setting the text. I used this instead:

cmdOutput.Append(Environment.NewLine + outLine.Data);
var str = cmdOutput.ToString();
textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = str; });
zeromus
  • 1,648
  • 13
  • 14