2009-01-14 125 views
1

我使用User32的ShowWindow方法從用戶隱藏窗口(cmd.exe)(主要是爲了防止它們關閉它)。當用戶打開表單時,進程開始並隱藏,然後當表單關閉時,進程被終止。但是,當表單再次打開時,它不會隱藏窗口(有時並不是第一次)有人可以幫助我嗎?User32的ShowWindow不按預期方式運行

[DllImport("User32")] 
    private static extern int ShowWindow(int hwnd, int nCmdShow); //this will allow me to hide a window 

    public ConsoleForm(Process p) { 
     this.p = p; 
     p.Start(); 
     ShowWindow((int)p.MainWindowHandle, 0); //0 means to hide the window. See User32.ShowWindow documentation SW_HIDE 

     this.inStream = p.StandardInput; 
     this.outStream = p.StandardOutput; 
     this.errorStream = p.StandardError; 

     InitializeComponent(); 

     wr = new watcherReader(watchProc); 
     wr.BeginInvoke(this.outStream, this.txtOut, null, null); 
     wr.BeginInvoke(this.errorStream, this.txtOut2, null, null); 
    } 

    private delegate void watcherReader(StreamReader sr, RichTextBox rtb); 
    private void watchProc(StreamReader sr, RichTextBox rtb) { 
     string line = sr.ReadLine(); 
     while (line != null && !stop && !p.WaitForExit(0)) { 
      //Console.WriteLine(line); 
      line = stripColors(line); 
      rtb.Text += line + "\n"; 

      line = sr.ReadLine(); 
     } 
    } 

    public void start(string[] folders, string serverPath) { 

     this.inStream.WriteLine("chdir C:\\cygwin\\bin"); 
     //this.inStream.WriteLine("bash --login -i"); 
     this.inStream.WriteLine(""); 
    } 

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) { 
     this.stop = true; 
     try { 
      this.p.Kill(); 
      this.p.CloseMainWindow(); 
     } catch (InvalidOperationException) { 
      return; 
     } 
    } 

回答

4

這將是這更簡單:

public ConsoleForm(Process p) { 
     this.p = p; 
     p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
     p.StartInfo.CreateNoWindow = true; 
     p.Start(); 

     this.inStream = p.StandardInput; 
     this.outStream = p.StandardOutput; 
     this.errorStream = p.StandardError; 

     InitializeComponent(); 

     wr = new watcherReader(watchProc); 
     wr.BeginInvoke(this.outStream, this.txtOut, null, null); 
     wr.BeginInvoke(this.errorStream, this.txtOut2, null, null); 
    } 
+0

工作完美,謝謝! – Malfist 2009-01-14 20:27:50

0

你檢查p.MainWindowHandle是否是一個有效的處理?它至少必須是非零的。嘗試撥打IsWindow進行確認。

MSDN suggests打電話WaitForInputIdle檢查前MainWindowHandle;您可能在新進程創建窗口之前訪問該屬性。不管怎樣,這家酒店本身就很危險,因爲流程並沒有真正的「主要」窗口的概念。所有的窗戶都是平等的。 .Net框架簡單地將第一個窗口指定爲主窗口,但該過程本身不需要以這種方式考慮事情。

另外,你有沒有考慮過最初隱藏進程,而不是啓動它,然後隱藏事實?設置進程的StartInfo屬性as Scotty2012 demonstrates