2013-01-11 54 views
6

我開發了一個實用程序,它將獲取列表中所有服務器的時間。想要隱藏cmd提示符屏幕

System.Diagnostics.Process p; 
string server_name = ""; 
string[] output; 
p = new System.Diagnostics.Process(); 
p.StartInfo.FileName = "net"; 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StandardOutput.ReadLine().ToString() 

執行此代碼時。 Cmd提示畫面即將到來。我想隱藏用戶。我能爲它做些什麼?

回答

11

你可以告訴的過程中不使用窗口或將其最小化:

// don't execute on shell 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.CreateNoWindow = true; 

// don't show window 
p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; 

UseShellExecute = false您可以重定向輸出:

// redirect standard output as well as errors 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.RedirectStandardError = true; 

當你這樣做,你的肩膀D使用輸出緩衝器的非同步讀出,以避免死鎖由於過度填充緩衝器:

StringBuilder outputString = new StringBuilder(); 
StringBuilder errorString = new StringBuilder(); 

p.OutputDataReceived += (sender, e) => 
      { 
       if (e.Data != null) 
       { 
        outputString.AppendLine("Info " + e.Data); 
       } 
      }; 

p.ErrorDataReceived += (sender, e) => 
      { 
       if (e.Data != null) 
       { 
        errorString.AppendLine("EEEE " + e.Data); 
       } 
      }; 
+0

UseShellExecute = false還將允許您將STDOUT和STDERR重定向到可能有用的流。 –

+0

@SrikanthVenugopalan因爲OP已經做到了,所以我把它放了出來。 – Matten

+1

是的,你是對的,我的不好。雖然,我個人覺得RedirectStandardError更重要。 –

0

試試這兩個

p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 

或檢查,這也

沒有任何窗口中運行的子進程,

使用CreateNoWindow屬性和設置UseShellExecute。

ProcessStartInfo info = new ProcessStartInfo(fileName, arg); 
info.CreateNoWindow = true; 
info.UseShellExecute = false; 
Process processChild = Process.Start(info); 

,我建議你去throught這個職位MSDN的:How to start a console app in a new window, the parent's window, or no window

4

嘗試用ProcessWindowStyle枚舉這樣;

p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.CreateNoWindow = true; 

隱藏的窗口樣式。窗口可以是可見的或隱藏的。系統通過不繪製來顯示隱藏的窗口。如果隱藏了一個窗口 ,它將被禁用。一個隱藏的窗口可以處理來自系統或其他窗口的消息,但它不能處理來自用戶或顯示輸出的輸入 。通常,應用程序可能會在定製窗口外觀時保留一個隱藏的新窗口,即 ,然後使窗口樣式爲Normal。要使用 ProcessWindowStyle.Hidden,則ProcessStartInfo.UseShellExecute 屬性必須是

0

添加系統參考。

using System.Diagnostics; 

然後使用此代碼在一個隱藏的CMD窗口中運行您的命令。

Process cmd = new Process(); 
cmd.StartInfo.FileName = "cmd.exe"; 
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
cmd.StartInfo.Arguments = "Enter your command here"; 
cmd.Start();