RealChildWindowFromPoint 僅搜尋直接子視窗,無法穿透重疊視窗定位最深層控制項。本文提供遞迴演算法:先定位最上層父視窗,再層層向下查找,實現 Spy++ 式的精準視窗拾取。
WindowFromPoint 取得滑鼠座標下的最上層視窗 hWndTop。WS_CHILD 樣式)作為搜尋根視窗 hRoot。ScreenToClient(hRoot, &pt) 轉換為根視窗用戶區座標。RealChildWindowFromPoint(hRoot, pt),若傳回子視窗且非自身,更新 hRoot = hChild 並繼續;否則中斷,hRoot 即為最深層視窗。int CGetWindowInfo::GetRealWindow(HWND* phWnd, POINT ptPoint) {
HWND hWndTop = WindowFromPoint(ptPoint); if (!hWndTop) return FALSE;
LONG style = GetWindowLong(hWndTop, GWL_STYLE);
HWND hRoot = (!GetParent(hWndTop) || GetDesktopWindow() == GetParent(hWndTop) || !(style & WS_CHILD))
? hWndTop : GetParent(hWndTop);
POINT ptClient = ptPoint; ScreenToClient(hRoot, &ptClient);
while (TRUE) {
HWND hChild = RealChildWindowFromPoint(hRoot, ptClient);
if (hChild && hChild != hRoot) hRoot = hChild;
else break;
}
*phWnd = hRoot; return TRUE;
}
取得視窗控制代碼後,可呼叫 SetWindowText 修改標題、GetWindowRect 取得位置、GetClassName 取得類別名等。範例程式實作「拖曳十字準星至目標視窗,顯示資訊並修改標題」功能,介面如圖二所示。