2009-06-17 8 views
6

Lorsque principale Form est une application - celle passée à Application.Run() - aForm.ShowInTaskBar/Process.MainWindowHandle

this.ShowInTaskBar = false; 

puis, une instance de Process représentant cette application a une MainWindowHandle de 0, ce qui signifie que Process.CloseMainWindow() ne le fait pas travail.

Comment puis-je contourner le problème? Je dois fermer proprement le Form via l'instance Process.

Répondre

2

J'ai trouvé une autre façon de le faire en revenant à Win32 stuff et en utilisant des titres de fenêtre. C'est en désordre, mais ça marche pour ma situation.

L'exemple a le menu contextuel d'une instance d'application fermant toutes les instances de cette application.

[DllImport("user32.dll")] 
public static extern int EnumWindows(EnumWindowsCallback x, int y); 
public delegate bool EnumWindowsCallback(int hwnd, int lParam); 
[DllImport("user32.dll")] 
public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount); 
[DllImport("user32.dll")] 
public static extern IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam); 
private void ContextMenu_Quit_All(object sender, EventArgs ea) 
{ 
    EnumWindowsCallback itemHandler = (hwnd, lParam) => 
    { 
     StringBuilder sb = new StringBuilder(1024); 
     GetWindowText(hwnd, sb, sb.Capacity); 

     if ((sb.ToString() == MainWindow.APP_WINDOW_TITLE) && 
      (hwnd != mainWindow.Handle.ToInt32())) // Don't close self yet 
     { 
      PostMessage(new IntPtr(hwnd), /*WM_CLOSE*/0x0010, 0, 0); 
     } 

     // Continue enumerating windows. There may be more instances to close. 
     return true; 
    }; 

    EnumWindows(itemHandler, 0); 
    // Close self .. 
}