win32-使用EnumWindows比较两个窗口的Z轴

通过使用EnumWindows()枚举窗口来手动确定EnumChildWindows()来直接确定哪个窗口在z轴上比另一个窗口高。

struct myEnumInfo
{
    HWND hwnd1;
    HWND hwnd2;
    HWND hwndOnTop;
};

BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam)
{
    myEnumInfo *info = (myEnumInfo*) lParam;

    // is one of the HWNDs found?  If so, return it...
    if ((hwnd == info->hwnd1) || (hwnd == info->hwnd2))
    {
        info->hwndOnTop = hwnd;
        return FALSE; // stop enumerating
    }

    return TRUE; // continue enumerating
}

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    myEnumInfo *info = (myEnumInfo*) lParam;

    // is one of the HWNDs found?  If so, return it...
    if ((hwnd == info->hwnd1) || (hwnd == info->hwnd2))
    {
        info->hwndOnTop = hwnd;
        return FALSE;
    }

    // enumerate this window's children...
    EnumChildWindows(hwnd, &EnumChildProc, lParam);

    // is one of the HWNDs found?  If so, return it...
    if (info->hwndOnTop)
        return FALSE; // stop enumerating

    return TRUE; // continue enumerating
}

HWND WhichOneIsOnTop(HWND hwnd1, HWND hwnd2)
{
    // is one of the HWNDs null? If so, return the other HWND...
    if (!hwnd1) return hwnd2;
    if (!hwnd2) return hwnd1;

    // is one of the HWNDs in the actual foreground? If so, return it...
    HWND fgWnd = GetForegroundWindow();
    if ((fgWnd) && ((fgWnd == hwnd1) || (fgWnd == hwnd2)))
        return fgWnd;

    myEnumInfo info;
    info.hwnd1 = hwnd1;
    info.hwnd1 = hwnd2;
    info.hwndOnTop = NULL;

    // are the HWNDs both children of the same parent?
    // If so, enumerate just that parent...
    HWND parent = GetAncestor(hwnd1, GA_PARENT);
    if ((parent) && (GetAncestor(hwnd2, GA_PARENT) == parent))
    {
        EnumChildWindows(parent, &EnumChildProc, (LPARAM)&info);
    }
    else
    {
        // last resort!! Enumerate all top-level windows and their children,
        // looking for the HWNDs wherever they are...
        EnumWindows(&EnumWindowsProc, (LPARAM)&info);
    }

    return info.hwndOnTop;
}

 

posted @ 2020-06-15 10:19  strive-sun  阅读(492)  评论(0编辑  收藏  举报