0

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
  • Pretty vague. Arbitrarily, take the first window in the list and call GetWindow(), passing GHWND_PREV. Check if it is in the list. Repeat until GetWindow() returns null. Commented Nov 21, 2014 at 17:39

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Jason. It works well for me. Lately I noticed that window handles which I get by calling EnumWindows() is already sorted by that order :D Thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.