вывод cmd в повторяющиеся строки текстового поля - PullRequest
0 голосов
/ 03 декабря 2018

Я пытаюсь создать тестовую программу для функции, которую хочу добавить в более крупный проект.Я пытаюсь получить вывод командного файла в текстовое поле, которое будет действовать как вывод командной строки inapp, с которым пользователь затем сможет взаимодействовать через приложение.Пользовательский ввод придет позже.Пока что у меня есть работающее приложение, поэтому оно читает пакетный вывод в режиме реального времени.Однако каждый раз, когда он обновляется, он берет точную копию всего, что должно отображаться в cmd, и вставляет его непосредственно под предыдущий вывод.В качестве теста я создал простой пакетный скрипт, который непрерывно проверяет 8.8.8.8 с аргументом -t.Вот мой код.

using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;

namespace ConsoleOutput_test
{
    public partial class Form1 : Form
    {
        private static StringBuilder sortOutput = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Process sortProcess;
            sortProcess = new Process();
            sortProcess.StartInfo.FileName = "test.bat";
            // Set UseShellExecute to false for redirection.
            sortProcess.StartInfo.CreateNoWindow = true;
            sortProcess.StartInfo.UseShellExecute = false;



            // Redirect the standard output of the sort command.  
            // This stream is read asynchronously using an event handler.
            sortProcess.StartInfo.RedirectStandardOutput = true;
            sortOutput = new StringBuilder("");

            // Set our event handler to asynchronously read the sort output.
            sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);

            // Redirect standard input as well.  This stream
            // is used synchronously.
            sortProcess.StartInfo.RedirectStandardInput = true;

            // Start the process.
            sortProcess.Start();



            // Start the asynchronous read of the sort output stream.
            sortProcess.BeginOutputReadLine();
            while (!sortProcess.HasExited)
            {
                Application.DoEvents(); // This keeps your form responsive by processing events
            }
        }

        private void SortOutputHandler(object sendingProcess,
            DataReceivedEventArgs outLine)
        {
            if (txtConsole.InvokeRequired) { txtConsole.BeginInvoke(new DataReceivedEventHandler(SortOutputHandler), new[] { sendingProcess, outLine }); }
            else
            {
            sortOutput.Append(Environment.NewLine + outLine.Data);
            txtConsole.AppendText(sortOutput.ToString());
            }
        }
    }
}

Итак, мы находимся там, где моя проблема.Когда я запускаю программу, она отображает то, что я хочу, в режиме реального времени, однако она копирует и вставляет обновленный вывод и вставляет его в текстовое поле прямо под последним обновлением.Пример ниже:

G:\ConsoleOutput test\ConsoleOutput Test\bin\Debug>ping 8.8.8.8 -t

G:\ConsoleOutput test\ConsoleOutput Test\bin\Debug>ping 8.8.8.8 -t

Pinging 8.8.8.8 with 32 bytes of data:

G:\ConsoleOutput test\ConsoleOutput Test\bin\Debug>ping 8.8.8.8 -t

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8:bytes=32 time=18ms TTL=253


G:\ConsoleOutput test\ConsoleOutput Test\bin\Debug>ping 8.8.8.8 -t

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8:bytes=32 time=18ms TTL=253
Reply from 8.8.8.8:bytes=32 time=21ms TTL=253

G:\ConsoleOutput test\ConsoleOutput Test\bin\Debug>ping 8.8.8.8 -t

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8:bytes=32 time=18ms TTL=253
Reply from 8.8.8.8:bytes=32 time=21ms TTL=253
Reply from 8.8.8.8:bytes=32 time=19ms TTL=253

etc

Вывод просто продолжается, как это.Я хочу отобразить вывод точно так, как он будет отображаться в окне cmd.

    G:\ConsoleOutput test\ConsoleOutput Test\bin\Debug>ping 8.8.8.8 -t

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8:bytes=32 time=18ms TTL=253
Reply from 8.8.8.8:bytes=32 time=21ms TTL=253
Reply from 8.8.8.8:bytes=32 time=19ms TTL=253
Reply from 8.8.8.8:bytes=32 time=18ms TTL=253
Reply from 8.8.8.8:bytes=32 time=21ms TTL=253
Reply from 8.8.8.8:bytes=32 time=19ms TTL=253
Reply from 8.8.8.8:bytes=32 time=18ms TTL=253
Reply from 8.8.8.8:bytes=32 time=21ms TTL=253
Reply from 8.8.8.8:bytes=32 time=19ms TTL=253

1 Ответ

0 голосов
/ 03 декабря 2018

делает именно то, что говорит ваш код:

      sortOutput.Append(Environment.NewLine + outLine.Data);
        txtConsole.AppendText(sortOutput.ToString());

вы говорите, добавьте новую строку в SortOutput, а затем добавьте весь вывод сортировки в текстовое поле.Вы, очевидно, получите повторяющиеся строки

просто сделайте

        txtConsole.AppendText(Environment.NewLine + outLine.Data);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...