C# 将cmd输出重定向到textBox
我正在将“命令提示符”重新创建到Windows窗体中。 应用程序工作不正常;我不知道为什么 当表单加载时,支持运行cmd.exe(将cmd信息加载到“TextBox\u Receive”中),但它没有;在“textBox_send”(发送输入)中写入任何命令之后;只有按“回车”键2或3次后,才会显示输入 你知道我在这里遗漏了什么吗C# 将cmd输出重定向到textBox,c#,redirect,cmd,output,C#,Redirect,Cmd,Output,我正在将“命令提示符”重新创建到Windows窗体中。 应用程序工作不正常;我不知道为什么 当表单加载时,支持运行cmd.exe(将cmd信息加载到“TextBox\u Receive”中),但它没有;在“textBox_send”(发送输入)中写入任何命令之后;只有按“回车”键2或3次后,才会显示输入 你知道我在这里遗漏了什么吗 public partial class Form1 : Form { // Global Variables: private static Str
public partial class Form1 : Form
{
// Global Variables:
private static StringBuilder cmdOutput = null;
Process p;
StreamWriter SW;
public Form1()
{
InitializeComponent();
textBox1.Text = Directory.GetCurrentDirectory();
// TextBox1 Gets the Current Directory
}
private void Form1_Load(object sender, EventArgs e)
{
checkBox1.Checked = true;
// This checkBox activates / deactivates writing commands into the "textBox_Send"
cmdOutput = new StringBuilder("");
p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.EnableRaisingEvents = true;
p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
p.Start();
SW = p.StandardInput;
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
private static void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
// I dont actually understand this part of the code; as this is a "copy" of a snippet i found somewhere. Although it fixed one of my issues to redirect.
{
if (!String.IsNullOrEmpty(outLine.Data))
{
cmdOutput.Append(Environment.NewLine + outLine.Data);
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Send "Enter Key" - Send Command
if (e.KeyChar == 13)
{
SW.WriteLine(txtbox_send.Text);
txtbox_receive.Text = cmdOutput.ToString();
txtbox_send.Clear();
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
// Enable / Disable Sending Commands
if (checkBox1.Checked)
txtbox_send.Enabled = true;
else
txtbox_send.Enabled = false;
}
}
}我认为您的问题在于使用
OutputDataReceived
。在:
该事件在上的异步读取操作期间启用
标准输出。要启动异步读取操作,必须
重定向进程的标准输出流,添加事件
OutputDataReceived事件的处理程序,并调用BeginOutputReadLine。
此后,每次处理结束时,OutputDataReceived都会收到事件信号
将一行写入重定向的StandardOutput流,直到
进程退出或调用CancelOutputRead
有关更多详细信息,请参见该页上的示例代码
然而,我不确定你是否需要走这条路。您是否尝试过直接从流中读取数据?您也可以尝试捕获错误数据 为此: 排队后
p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
输入这一行
p.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler);
cmd.exe也可能有问题
谢谢!=)我已经做了代码和重定向完美!谢谢我忘了。