Answer the question
In order to leave comments, you need to log in
How in C# to create a child process that is used by several methods, and then destroy it?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Process myprocess;
public StreamWriter mywriter;
public StreamReader myreader;
// асинхронно посылает на вход myConsoleApp.exe
private async void MyWriteAsync(string cm)
{
await mywriter.WriteLineAsync(cm);
}
// постоянно ожидает ответ от myConsoleApp.exe,
// полученные строки пишет в textBox1
private async void MyReadAsync()
{
string output;
do
{
output = await myreader.ReadLineAsync();
textBox1.Text += output + "\r\n";
textBox1.Select(textBox1.Text.Length, 0);
textBox1.ScrollToCaret();
} while (output != null);
}
// запуск дочернего процесса myConsoleApp.exe
private void Button1_Click(object sender, EventArgs e)
{
textBox1.Text = "ok\r\n";
using (myprocess = new Process())
{
myprocess.StartInfo.FileName = "myConsoleApp.exe";
myprocess.StartInfo.UseShellExecute = false;
myprocess.StartInfo.CreateNoWindow = true;
myprocess.StartInfo.RedirectStandardInput = true;
myprocess.StartInfo.RedirectStandardOutput = true;
myprocess.Start();
mywriter = myprocess.StandardInput;
myreader = myprocess.StandardOutput;
mywriter.WriteLine("hello");
MyReadAsync();
}
}
// отправить команду из textBox2 на вход myConsoleApp.exe
private void Button2_Click(object sender, EventArgs e)
{
string cm = textBox2.Text;
textBox1.Text += cm + "\r\n";
textBox1.Select(textBox1.Text.Length, 0);
textBox1.ScrollToCaret();
MyWriteAsync(cm);
}
// при закрытии окна завершить дочерний процесс
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
myprocess.Close();
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question