如何:给定HWND,发现窗口是否是模态

Cod*_*ion 9 c# winapi modal-dialog outlook-2007 inspector

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

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

感谢帮助!

编辑:为什么我的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");
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Bre*_*McK 8

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

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

这应该捕获所有标准的Win32风格模式对话框.

请注意,父母和所有者是微妙不同的概念; 这是你想在这里查看的主人.这可能会造成混淆,因为可以的getParent返回主人... -更多细节从雷蒙德陈在这里.