Get handle of top window (Sort windows by Z index)

1.9k Views Asked by At

I am trying to write a method which takes List of window handles and returns handle of the window which has highest z index among others. But in vain. Can anybody give me a suggestion how to do that?

1

There are 1 best solutions below

1
On BEST ANSWER

I'll help you out:

[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;
}