获取顶部窗口的句柄(按Z索引排序窗口)

时间:2014-11-21 17:04:43

标签: c# .net winapi z-index handle

我正在尝试编写一个方法,该方法接受窗口句柄列表并返回具有最高z索引的窗口的句柄。但徒劳无功。任何人都可以给我一个如何做的建议吗?

1 个答案:

答案 0 :(得分:2)

我会帮助你的:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);

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
}

private IntPtr GetTopmostHwnd(List<IntPtr> hwnds)
{
    var topmostHwnd = IntPtr.Zero;

    if (hwnds != null && hwnds.Count > 0)
    {
        var hwnd = hwnds[0];

        while (hwnd != IntPtr.Zero)
        {
            if (hwnds.Contains(hwnd))
            {
                topmostHwnd = hwnd;
            }

            hwnd = GetWindow(hwnd, GetWindow_Cmd.GW_HWNDPREV);
        }
    }

    return topmostHwnd;
}