What I intend to do is build an application which, among other things, will have a command line embedded in it just like some IDEs do (something I find extremely useful).
This is the code that I have so far, do note that it's a Winforms project:
public partial class Form1 : Form
{
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
p.StartInfo = info;
p.Start();
}
private void button1_Click(object sender, EventArgs e) {
using(StreamWriter sw = p.StandardInput) {
if(sw.BaseStream.CanWrite) {
sw.WriteLine(textBox1.Text);
}
}
textBox2.Text = p.StandardOutput.ReadToEnd();
textBox3.Text = p.StandardError.ReadToEnd();
p.WaitForExit();
}
}
}
As you can see there are 3 textboxes and one button:
- textbox1 is for entering the command
- textbox2 is for stdout
- textbox3 is for stderr
On to my problem:
I can only input _one_ command because after executing it, my CMD window vanishes. I know it dies off because I've set
info.Create`NoWindow = false;
and it indeed vanishes (plus if I try to enter another command I get an unhandled exception).
How would I go on about keeping my CMD window 'alive' so that I can use it as much as I please? In short I want to truly mimic CMD behavior.
Feel free to ask for more information if something is not clear.
What I tried:
I've tried adding
info.Attributes = "/K";
since I know that /K should keep the CMD alive. I've also read that
p.WaitForExit();
should keep the CMD alive, but from what I figured this is only for the purpose of reading the output. Needless to say, I do not need that since I'm already redirecting its output.
Please do note that I need that process alive so I can easily navigate using
cd
and executing a sequence of commands when needed, such as when accessing
ftp
or
mysql
. I know I can work around these two examples with parameters, but that is not the case for every application. In short, spawning a new process every time is not something I want.
Thank you in advance or your responses.