0
嗨我想开始一个单一的cmd进程,从中我可以从我的Windows应用程序窗体读取和写入。我想强调一下,我不想继续为我输入的每个命令创建一个新的cmd进程。我的代码现在很混乱。 。 。 我有一个Windows窗体应用程序现在只有2个文本框和一个按钮。 Textbox1用于输出。 Textbox2为输入。 按钮用于发送输入。读取和写入命令到一个单一的CMD过程
Process cmd = new Process();
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = "cmd.exe",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardInput = true
};
StreamReader sr;
StreamWriter sw;
private void Form1_Load(object sender, EventArgs e)
{
cmd.StartInfo = psi;
cmd.Start();
sr = cmd.StandardOutput;
sw = cmd.StandardInput;
sw.AutoFlush = true;
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(GetOutput));
t.Start();
}
delegate void Write(string Text);
private void SetTextBox(string Text)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new Write(SetTextBox),Text);
}
else
textBox1.Text += Text;
}
private void GetOutput()
{
while (true)
{
if (sr.Peek() != -1)
SetTextBox(sr.ReadToEnd());
else
System.Threading.Thread.Sleep(1000);
}
}
private void button1_Click(object sender, EventArgs e)
{
sw.WriteLine(textBox2.Text);
textBox2.Clear();
}
什么不起作用? – 2012-08-17 08:32:55
我输入一个命令后,cmd.exe自动关闭。我希望它保持打开状态,以便我可以根据需要输入其他命令 – RStyle 2012-08-17 10:32:34
如cd到目录。然后执行一些命令。然后cd到另一个目录。这要求我打开cmd以执行上述操作,并且每次执行命令时都不关闭。 – RStyle 2012-08-17 10:40:07