【问题标题】:Form.ShowInTaskBar / Process.MainWindowHandleForm.ShowInTaskBar / Process.MainWindowHandle
【发布时间】:2009-06-17 11:28:59
【问题描述】:
当应用程序的主 Form - 传递给 Application.Run() 的那个 - 有
this.ShowInTaskBar = false;
那么,代表该应用程序的Process 实例具有0 的MainWindowHandle,这意味着Process.CloseMainWindow() 不起作用。
我该如何解决这个问题?我需要通过Process 实例彻底关闭Form。
【问题讨论】:
标签:
c#
.net
windows
winforms
taskbar
【解决方案1】:
我找到了一种替代方法,即退回到 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 ..
}