如何知道子进程的标准输出行需要覆盖前一行?

时间:2021-04-12 18:51:13

标签: c# console redirectstandardoutput

我从 WinForms 应用程序调用了一个外部控制台应用程序。当该应用程序在控制台中运行时,它会输出其进度,并且进度线会像动画一样更新。但是当我将它重定向到 WinForms,并将标准输出附加到一个文本框时,当然,所有的进度行都被附加了。所以,我想我需要一种方法来获取“更新现有行,而不是添加新行”消息。

为了测试这一点,我创建了一个控制台应用程序,它使用 existing question 更新输出行。但是使用这个控制台应用程序,WinForms 应用程序只得到第一行“正在下载 0%...”,没有更多。我不知道出了什么问题。

如何在 WinForms 应用中知道“这一行覆盖了最后一行”?

孩子

namespace Child
{
    class Program
    {
        public static void ClearCurrentConsoleLine()
        {
            int currentLineCursor = Console.CursorTop;
            Console.SetCursorPosition(0, Console.CursorTop);
            Console.Write(new string(' ', Console.WindowWidth));
            Console.SetCursorPosition(0, currentLineCursor);
        }

        static void Main(string[] args)
        {
            for(int i = 0; i<=100; i+=10)
            {
                Console.WriteLine($"Downloading {i}%...");
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Thread.Sleep(200);
                ClearCurrentConsoleLine();
            }
        }
}

家长

namespace Parent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var si = new ProcessStartInfo();
            si.RedirectStandardOutput = true;
            si.CreateNoWindow = true;
            si.FileName = "..\\net5.0\\Child.exe";
            si.UseShellExecute = false;

            var p = new Process();
            p.StartInfo = si;
            p.OutputDataReceived += P_OutputDataReceived;
            p.Start();
            p.BeginOutputReadLine();
        }

        void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            this.Invoke(new Action(() => {
                textBox1.AppendText(e.Data);
            }));
        }
    }
}

0 个答案:

没有答案
相关问题