using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace MyNamespace
{
public partial class MyForm : Form
{
private Process cmdProcess;
public MyForm()
{
InitializeComponent();
InitializeCmd();
}
private void InitializeCmd()
{
cmdProcess = new Process();
cmdProcess.StartInfo.FileName = "cmd.exe";
cmdProcess.StartInfo.CreateNoWindow = true;
cmdProcess.StartInfo.UseShellExecute = false;
cmdProcess.StartInfo.RedirectStandardInput = true;
cmdProcess.StartInfo.RedirectStandardOutput = true;
cmdProcess.StartInfo.RedirectStandardError = true;
// ascunde bara de titlu si butoanele
cmdProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmdProcess.Start();
StreamWriter cmdStreamWriter = cmdProcess.StandardInput;
StreamReader cmdStreamReader = cmdProcess.StandardOutput;
StreamReader cmdErrorReader = cmdProcess.StandardError;
// adaugă controlul la form
TextBox cmdControl = new TextBox();
cmdControl.Multiline = true;
cmdControl.Dock = DockStyle.Fill;
cmdControl.ScrollBars = ScrollBars.Vertical;
cmdControl.Font = new System.Drawing.Font("Courier New", 10);
Controls.Add(cmdControl);
// afișează output-ul din terminal în control
cmdStreamReader.BaseStream.BeginRead(new byte[1], 0, 0, null, null);
cmdStreamReader.DataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
cmdControl.Invoke(new Action(() =>
{
cmdControl.AppendText(e.Data + Environment.NewLine);
}));
}
};
// citește input de la utilizator și trimite la terminal
cmdControl.KeyDown += (s, e) =>
{
if (e.KeyCode == Keys.Enter)
{
cmdStreamWriter.WriteLine(cmdControl.Text);
cmdControl.Clear();
}
};
// afișează erorile în consolă
cmdErrorReader.BaseStream.BeginRead(new byte[1], 0, 0, null, null);
cmdErrorReader.DataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Debug.WriteLine(e.Data);
}
};
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
cmdProcess?.Kill();
}
}
}