2012-08-17 56 views
0

嗨我想開始一個單一的cmd進程,從中我可以從我的Windows應用程序窗體讀取和寫入。我想強調一下,我不想繼續爲我輸入的每個命令創建一個新的cmd進程。我的代碼現在很混亂。 。 。 我有一個Windows窗體應用程序現在只有2個文本框和一個按鈕。 Textbox1用於輸出。 Textbox2爲輸入。 按鈕用於發送輸入。讀取和寫入命令到一個單一的CMD過程

Process cmd = new Process(); 
    ProcessStartInfo psi = new ProcessStartInfo() 
    { 
     FileName = "cmd.exe", 

     UseShellExecute = false, 
     CreateNoWindow = true, 
     RedirectStandardOutput = true, 
     RedirectStandardInput = true 
    }; 

    StreamReader sr; 
    StreamWriter sw; 


    private void Form1_Load(object sender, EventArgs e) 
    { 
     cmd.StartInfo = psi; 
     cmd.Start(); 

     sr = cmd.StandardOutput; 

     sw = cmd.StandardInput; 
     sw.AutoFlush = true; 

     System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(GetOutput)); 
     t.Start(); 

    } 

    delegate void Write(string Text); 
    private void SetTextBox(string Text) 
    { 
     if (textBox1.InvokeRequired) 
     { 
      textBox1.Invoke(new Write(SetTextBox),Text); 
     } 
     else 
      textBox1.Text += Text; 
    } 

    private void GetOutput() 
    { 
     while (true) 
     { 
      if (sr.Peek() != -1) 
       SetTextBox(sr.ReadToEnd()); 
      else 
       System.Threading.Thread.Sleep(1000); 

     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     sw.WriteLine(textBox2.Text); 
     textBox2.Clear(); 
    } 
+0

什麼不起作用? – 2012-08-17 08:32:55

+0

我輸入一個命令後,cmd.exe自動關閉。我希望它保持打開狀態,以便我可以根據需要輸入其他命令 – RStyle 2012-08-17 10:32:34

+0

如cd到目錄。然後執行一些命令。然後cd到另一個目錄。這要求我打開cmd以執行上述操作,並且每次執行命令時都不關閉。 – RStyle 2012-08-17 10:40:07

回答

0

嘗試使用/ k參數,它告訴CMD.exe打開,運行指定的命令,然後保持窗口打開。