将控制台输出重定向到单独程序中的文本框 [英] Redirect console output to textbox in separate program

查看:25
本文介绍了将控制台输出重定向到单独程序中的文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Windows 窗体应用程序,它需要我调用一个单独的程序来执行任务.该程序是一个控制台应用程序,我需要将控制台的标准输出重定向到我程序中的 TextBox.

I'm developing an Windows Forms application that requires me to call a separate program to perform a task. The program is a console application and I need to redirect standard output from the console to a TextBox in my program.

我从我的应用程序执行程序没有问题,但我不知道如何将输出重定向到我的应用程序.我需要在程序运行时使用事件捕获输出.

I have no problem executing the program from my application, but I don't know how to redirect the output to my application. I need to capture output while the program is running using events.

在我的应用程序停止并且文本以随机间隔不断变化之前,控制台程序不会停止运行.我正在尝试做的只是从控制台挂钩输出以触发事件处理程序,然后可以使用该事件处理程序更新 TextBox.

The console program isn't meant to stop running until my application stops and the text changes constantly at random intervals. What I'm attempting to do is simply hook output from the console to trigger an event handler which can then be used to update the TextBox.

我使用 C# 编写程序并使用 .NET 框架进行开发.原始应用程序不是 .NET 程序.

I am using C# to code the program and using the .NET framework for development. The original application is not a .NET program.

这是我正在尝试做的示例代码.在我的最终应用程序中,我将用代码替换 Console.WriteLine 以更新 TextBox.我试图在我的事件处理程序中设置一个断点,但它甚至没有达到.

Here's example code of what I'm trying to do. In my final app, I'll replace Console.WriteLine with code to update the TextBox. I tried to set a breakpoint in my event handler, and it isn't even reached.

    void Method()
    {
        var p = new Process();
        var path = @"C:ConsoleApp.exe";

        p.StartInfo.FileName = path;
        p.StartInfo.UseShellExecute = false;
        p.OutputDataReceived += p_OutputDataReceived;

        p.Start();
    }

    static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(">>> {0}", e.Data);
    }

推荐答案

这对我有用:

void RunWithRedirect(string cmdPath)
{
    var proc = new Process();
    proc.StartInfo.FileName = cmdPath;

    // set up output redirection
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.RedirectStandardError = true;    
    proc.EnableRaisingEvents = true;
    proc.StartInfo.CreateNoWindow = true;
    // see below for output handler
    proc.ErrorDataReceived += proc_DataReceived;
    proc.OutputDataReceived += proc_DataReceived;

    proc.Start();

    proc.BeginErrorReadLine();
    proc.BeginOutputReadLine();

    proc.WaitForExit();
}

void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
    // output will be in string e.Data
}

这篇关于将控制台输出重定向到单独程序中的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆