问题描述
问题:我想从winforms控制cmd.exe.
Question: I want to control cmd.exe from winforms.
我并不是指单个进程中的每个命令,带有启动信息,然后停止.
I DO NOT mean every command in a single process, with startupinfo, and then stop.
我的意思是例如启动(我的)SQL 或 GDB 命令提示符、发送命令、接收答案、发送下一个命令、接收下一个答案、停止 SQL 命令提示符
退出进程.
I mean for example start the (My) SQL or GDB command prompt, send command, receive answer, send next command, receive next answer, stop SQL command prompt
exit process.
基本上我想在任何控制台应用程序之上编写一个 GUI.
Basically I want to write a GUI on top of any console application.
我希望将 cmd.exe 的输出重定向到一个文本字段,而输入来自另一个文本字段(按下 enter/OK 按钮).
I want to have the output from cmd.exe redirected to a textfield, and the input coming from another textfield (on press enter/OK button).
我没有找到任何样品.有什么办法吗?
I don't find any samples for this. Is there a way?
推荐答案
代码项目
祝你好运!
-我认为这更像是它,我创建了一个简单的表单,2 个文本框和三个按钮.第一个文本框用于输入命令,第二个(多行)显示结果.
- I think this is more like it, I created a simple form, 2 textboxes and three buttons. First textbox is for command entry, the second (multiline), displays the result.
第一个按钮执行命令,第二个按钮更新结果(因为结果是异步读取的)
The first button executes the command, the second button updates the result (because results are read async)
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private static StringBuilder cmdOutput = null;
Process cmdProcess;
StreamWriter cmdStreamWriter;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmdOutput = new StringBuilder("");
cmdProcess = new Process();
cmdProcess.StartInfo.FileName = "cmd.exe";
cmdProcess.StartInfo.UseShellExecute = false;
cmdProcess.StartInfo.CreateNoWindow = true;
cmdProcess.StartInfo.RedirectStandardOutput = true;
cmdProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
cmdProcess.StartInfo.RedirectStandardInput = true;
cmdProcess.Start();
cmdStreamWriter = cmdProcess.StandardInput;
cmdProcess.BeginOutputReadLine();
}
private void btnExecute_Click(object sender, EventArgs e)
{
cmdStreamWriter.WriteLine(textBox2.Text);
}
private void btnQuit_Click(object sender, EventArgs e)
{
cmdStreamWriter.Close();
cmdProcess.WaitForExit();
cmdProcess.Close();
}
private void btnShowOutput_Click(object sender, EventArgs e)
{
textBox1.Text = cmdOutput.ToString();
}
private static void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
cmdOutput.Append(Environment.NewLine + outLine.Data);
}
}
}
}
在截图中你可以看到我输入了cd命令来改变目录,下一个命令在这个目录(dir)中执行.
In the screenshot you can see that I entered the cd command to change directory and the next command executed in this directory (dir).
这篇关于从 Winforms 控制 cmd.exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!