Sending input/getting output from a console application (C#/WinForms)

前端 未结 4 483
你的背包
你的背包 2020-12-06 03:48

I have a form with 3 controls:

  1. A textbox for the user to enter commands to send to a console application,
  2. A button to confirm the commands to be sent
4条回答
  •  半阙折子戏
    2020-12-06 04:25

    The best solution I have found is:

    private void Redirect(StreamReader input, TextBox output)
    {
        new Thread(a =>
        {
            var buffer = new char[1];
            while (input.Read(buffer, 0, 1) > 0)
            {
                output.Dispatcher.Invoke(new Action(delegate
                {
                    output.Text += new string(buffer);
                }));
            };
        }).Start();
    }
    
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                CreateNoWindow = true,
                FileName = "app.exe",
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
            }
        };
        if (process.Start())
        {
            Redirect(process.StandardError, textBox1);
            Redirect(process.StandardOutput, textBox1);
        }
    }
    

提交回复
热议问题