How to capture text that another console program writes on the screen

3

My Windows Forms program runs another console program. This second writes messages on the screen during execution. I want to know if it has to prevent the execution of the other program from opening the console, and instead the printf of the other program (which is written in C ++) are displayed in my TextBox.

Practical example: Imagex is a Microsoft console program. One user created Gimagex that has a graphical interface and runs Imagex and all text outputs appear on Gimagex.

    
asked by anonymous 10.07.2015 / 19:47

1 answer

2

Before doing process.Start() put true into process.StartInfo.RedirectStandardOutput and false into process.StartInfo.UseShellExecute

Assuming you want to receive the output of the ConsoleApplication.exe program in a ListBox

public Form1()
{
    InitializeComponent();
    StartProcess();
}

public void StartProcess()
{
    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "ConsoleApplication.exe";
    p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);

    p.Start();
    p.BeginOutputReadLine();
    p.WaitForExit();
    p.Close();
}

private void OutputHandler(object process, DataReceivedEventArgs e)
{
    if (!String.IsNullOrEmpty(e.Data))
    {
        listBox1.Items.Add(e.Data);
    }
}

Note: Note that ConsoleApplication.exe does not require any user input during its execution.

Sources:
ProcessStartInfo. RedirectStandardOutput Property
Process .BeginOutputReadLine Method

    
10.07.2015 / 23:35