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

Asked

Viewed 688 times

3

My Windows Forms program runs another console program. This second one writes messages on the screen while running. I want to know if you can prevent the execution of the other program from opening the console, and instead, the printf of the other program (which is written in C++) is displayed in my Textbox.

Practical example: Imagex is a Microsoft console program. A user created Gimagex which has a graphical interface and runs Imagex and all text outputs appear in Gimagex.

1 answer

2


Before making process.Start() place true in process.StartInfo.RedirectStandardOutput and false in process.StartInfo.UseShellExecute

Supposing you want to receive the output of the program Consoleapplication.exe in a Listbox do so:

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: I assume that Consoleapplication.exe does not require any user intervention(input) throughout its execution.

Sources:
Processstartinfo.Redirectstandardoutput Property
Process.Beginoutputreadline Method

  • In this scheme the console still opens but without text, but the problem is that in the line that passes the text to my Textbox (which is called "Output") generates the exception: Operação entre threads inválida: controle 'Saida' acessado de um thread que não é aquele no qual foi criado.. And yes, the console executable does not require user intervention.

  • Open the console is just like that. Regarding the thread if you are executing my code in another thread no visual component can be accessed. Use a Task along with a Iprogress

Browser other questions tagged

You are not signed in. Login or sign up in order to post.