2013-05-10 88 views
0

我正在将“命令提示符”重新创建到Windows窗体中。 该应用程序无法正常工作;我不能确切地说明原因。C#重定向cmd输出到文本框

当表单加载它运行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; 
    } 
} 

}

回答

1

我觉得你的问题是使用的OutputDataReceived。在documentation

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

请参阅该页面上的示例代码以获取更多详细信息。

但是 - 我不确定你需要走那条路线。您是否试过直接从StandardOutput流中读取数据?

+0

谢谢! =)我重新编写了代码并完全重定向! – Richard 2013-05-11 16:52:15

1

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

要做到这一点:

你行后

p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler); 

进入这一行

p.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler); 

它也可能与cmd.exe一个问题。

+0

谢谢!我忘了那个。 – Richard 2013-05-11 16:52:52