Form.ShowInTaskBar / Process.MainWindowHandle

6

当一个应用程序的主要 Form - 传递给 Application.Run() 的那个 - 有

this.ShowInTaskBar = false;

那么,表示该应用程序的Process实例具有MainWindowHandle0,这意味着Process.CloseMainWindow()无法起作用。

我该怎么办?我需要通过Process实例清洁关闭Form

1个回答

2
我找到了一种替代方法,通过回到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 ..
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接