C#将cmd输出重定向到textBox

时间:2013-05-10 23:24:43

标签: c# redirect cmd output

我在Windows窗体中重新创建“命令提示符”。 该应用程序无法正常工作;我无法确定原因。

当表单Loads它被用来运行cmd.exe(将cmd信息加载到“TextBox_Receive”),但它没有;并且在“textBox_send”(发送输入)中写入任何命令之后;它只会在按下“Enter”键2或3次后显示输入。

知道我在这里缺少什么吗?

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;
    }
}

}

2 个答案:

答案 0 :(得分:1)

我认为您的问题是使用OutputDataReceived。在documentation

  

在异步读取操作期间启用该事件   StandardOutput。要启动异步读取操作,您必须   重定向Process的StandardOutput流,添加您的事件   处理OutputDataReceived事件,并调用BeginOutputReadLine。   此后,每次进程时OutputDataReceived事件都会发出信号   将一行写入重定向的StandardOutput流,直到   进程退出或调用CancelOutputRead。

有关详细信息,请参阅该页面上的示例代码。

但是 - 我不确定你是否需要走那条路。您是否尝试过直接从StandardOutput信息流中阅读?

答案 1 :(得分:1)

您也可以尝试捕获错误数据。

要做到这一点:

在你的行之后

p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);

输入此行

p.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler);

cmd.exe可能也存在问题。

相关问题