从两个窗口返回前景窗口

Return the foreground window from two windows

本文关键字:窗口 返回 两个      更新时间:2023-10-16

win32编程中,给定两个重叠的窗口,w1w2,如何获取前景窗口?

GetForegroundWindow()为您提供实际的前景窗口(具有当前焦点的窗口(。前景中一次只能有 1 个窗口。

如果 2 个窗口都不是前景窗口,则没有 API 可用于直接确定哪个窗口在 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;
}