2011-12-22 4 views
2

CMDをC#RichTextAreaから起動して制御しようとしています(コマンドを1つだけ実行するのではなく、コマンドプロンプトとまったく同じです)。動作するように見えますが、別の入力を送信するまでは、出力の最終行(たとえば、実行後には従来の「任意のキーを押し続ける...」やカーソルの前の作業ディレクトリ)をリダイレクトしません。それは基本的なコードです:cmd.exe出力/入力(C#)をリダイレクトするときに最後の行が見つからない

class CmdPanel : Panel 
{ 
    CmdTextArea textArea; 

    Process winCmdProcess; 

    public CmdPanel() 
    { 
     this.BorderStyle = BorderStyle.None; 

     textArea = new CmdTextArea(this); 
     this.Controls.Add(textArea); 

     this.InitializeComponent(); 
     this.StartShell(); 
    } 

    public void StartShell() 
    { 
     this.winCmdProcess = new Process(); 
     this.winCmdProcess.StartInfo.FileName = "cmd.exe"; 
     this.winCmdProcess.StartInfo.UseShellExecute = false; 
     this.winCmdProcess.StartInfo.RedirectStandardOutput = true; 
     this.winCmdProcess.StartInfo.RedirectStandardError = true; 
     this.winCmdProcess.StartInfo.RedirectStandardInput = true; 
     this.winCmdProcess.StartInfo.CreateNoWindow = true; 
     this.winCmdProcess.OutputDataReceived += new DataReceivedEventHandler(winCmdProcess_OutputDataReceived); 
     this.winCmdProcess.ErrorDataReceived += new DataReceivedEventHandler(winCmdProcess_ErrorDataReceived); 

     this.winCmdProcess.Start(); 
     this.winCmdProcess.BeginOutputReadLine(); 
     this.winCmdProcess.BeginErrorReadLine(); 

    } 

    /// <summary> 
    /// Executes a given command 
    /// </summary> 
    /// <param name="command"> A string that contains the command, with args</param> 
    public void Execute(String command) 
    { 
     if (!string.IsNullOrWhiteSpace(command)) 
     { 
      this.winCmdProcess.StandardInput.WriteLine(command); 
     } 
    } 

    private void winCmdProcess_OutputDataReceived(object sendingProcess, DataReceivedEventArgs outLine) 
    { 
     this.ShowOutput(outLine.Data); 
    } 

    private void winCmdProcess_ErrorDataReceived(object sendingProcess, DataReceivedEventArgs outLine) 
    { 
     this.ShowOutput(outLine.Data); 
    } 

    delegate void ShowOutputCallback(string text); 
    private void ShowOutput(string text) 
    { 
     if (this.textArea.InvokeRequired) 
     { 
      ShowOutputCallback call = new ShowOutputCallback(ShowOutput); 
      this.Invoke(call, new object[] { text }); 
     } 
     else 
     { 
      this.textArea.AppendText(text + Environment.NewLine); 
     } 
    } 

    private void InitializeComponent() 
    { 

    } 

(私はテキストエリアの詳細を与えていないんだけど、それはメソッドを実行するために新しいコマンドを送信します。)

私は何をしないのですか?

答えて

1

イベントwon't fire unless a newline is output(またはストリームが閉じられるかバッファがいっぱいになるまで)、部分行またはコマンドプロンプトがイベントをトリガしません。

+0

それで「強制」する方法はありますか?私は別のスレッドからStandardOutputを読み取るいくつかの解決策を見つけました... – TheUnexpected

+0

私はポーリング(すなわち、タイマを使用する)ではなく、イベントに頼っている(はい、それは醜いです)。 – jdigital