Form.ShowInTaskBar / Process.MainWindowHandle

当一个应用程序的主Form – 一个传递给Application.Run() – 的Form

 this.ShowInTaskBar = false; 

那么表示该应用程序的Process一个实例的MainWindowHandle0 ,这意味着Process.CloseMainWindow()不起作用。

我怎样才能解决这个问题? 我需要通过Process实例干净地closuresForm

我找到了一种替代方法,通过回到Win32的东西,并使用窗口标题。 这是混乱的,但它适用于我的情况。

该示例具有关闭该应用程序的所有实例的一个应用程序实例的上下文菜单。

 [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 .. }