11

对于我处理的任何给定窗口,我需要一种方法来确定给定窗口是否为模态窗口。

据我所知,没有任何方法可以做到这一点,这就是为什么我需要一些聪明的解决方法来解决这个问题!

帮助表示赞赏!

编辑:为什么我的 GetWindow(,GW_OWNER) 失败了?:(

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [DllImport("user32.dll", SetLastError = true)]
    internal static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);
    [DllImport("user32.dll", ExactSpelling = true)]
    internal static extern IntPtr GetAncestor(IntPtr hwnd, GetAncestor_Flags gaFlags);
    [DllImport("user32.dll", SetLastError = false)]
    internal static extern IntPtr GetDesktopWindow();
    [DllImport("user32.dll", SetLastError = true)]
    internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    const UInt32 WS_DISABLED = 0x8000000;


    internal enum GetAncestor_Flags
    {
        GetParent = 1,
        GetRoot = 2,
        GetRootOwner = 3
    }

    internal enum GetWindow_Cmd : uint
    {
        GW_HWNDFIRST = 0,
        GW_HWNDLAST = 1,
        GW_HWNDNEXT = 2,
        GW_HWNDPREV = 3,
        GW_OWNER = 4,
        GW_CHILD = 5,
        GW_ENABLEDPOPUP = 6
    }



IntPtr _inspHwnd = FindWindow("rctrl_renwnd32", inspector.Caption); // searching for a window with this name
        if (_inspHwnd.ToInt32() != 0) // found window with this name
        {
            IntPtr _ownerHwnd = GetWindow(_inspHwnd, GetWindow_Cmd.GW_OWNER);
            if (_ownerHwnd.ToInt32() != 0)
            {
                IntPtr _ancestorHwnd = GetAncestor(_ownerHwnd, GetAncestor_Flags.GetParent);
                if (_ancestorHwnd == GetDesktopWindow())
                {
                    if (GetWindowLong(_ancestorHwnd, -16) == WS_DISABLED) 
                    { 
                        // inspector is probably modal if you got all the way here
                        MessageBox.Show("modal flag tripped");
                    }
                }
            }
        }
4

3 回答 3

8

模态窗口通常通过禁用其所有者来工作,其中所有者是顶级窗口。因此,如果您测试这种情况,您应该了解对话框是否是模态的。

  • 检查 HWND 实际上是一个顶级对话框,而不是子窗口
  • 获取所有者 (GetWindow(GW_OWNER))
  • 检查所有者本身是否是顶级窗口(例如 GetAncestor(GA_PARENT)==GetDesktopWindow())
  • 检查所有者是否被禁用 (GetWindowLong(GWL_STYLE) & WS_DISABLED)

这应该会捕获所有标准 Win32 样式的模式对话框。

请注意,父母和所有者是微妙不同的概念;这是您要在此处查看的所有者。这可能会让人感到困惑,因为 GetParent 可以返回所有者...... - Raymond Chen 的更多细节在这里

于 2011-04-26T00:13:38.353 回答
2

我不确定 BrendanMck 的解决方案是否总是正确的。假设窗口 W 首先显示一个无模式对话框 A,然后显示一个模式对话框 B。A 和 B 都将 W 作为其父窗口。在显示 B 时,W 被禁用,因此将算法应用于 A 和 B 将报告它们都是模态对话框。

于 2012-11-07T16:15:59.947 回答
-1

我只是写 GetWindowLong(GetWindow(Hwnd, GW_OWNER), GWL_STYLE) & WS_DISABLED & WS_POPUP 在我的代码中。

于 2012-06-20T07:57:01.853 回答