在单独的程序中将控制台输出重定向到文本框

49 .net c# console textbox winforms

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

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

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

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

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

    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);
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ham 70

这对我有用:

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
}
Run Code Online (Sandbox Code Playgroud)

  • 我发现有时(在程序退出时)e.Data为null,所以你必须检查e.Data!= null! (5认同)
  • 我们不需要设置`UseShellExecute = false`来重定向输出吗? (3认同)

Ahm*_*aid 5

您可以使用以下代码

        MemoryStream mem = new MemoryStream(1000);
        StreamWriter writer = new StreamWriter(mem);
        Console.SetOut(writer);

        Assembly assembly = Assembly.LoadFrom(@"C:\ConsoleApp.exe");
        assembly.EntryPoint.Invoke(null, null);
        writer.Close();

        string s = Encoding.Default.GetString(mem.ToArray());
        mem.Close();
Run Code Online (Sandbox Code Playgroud)

  • 如果“C:\ConsoleApp.exe”不是 .Net 应用程序,它将不会运行! (8认同)