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

this.ShowInTaskBar = false;

然后,表示该应用程序的 Process 的实例具有 0 MainWindowHandle ,这意味着 Process.CloseMainWindow()不起作用。

我该如何解决这个问题?我需要通过 Process 实例干净地关闭 Form

有帮助吗?

解决方案

我找到了另一种方法,通过回到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 ..
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top