首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

打造類 Spy++ 視窗搜尋工具:RealChildWindowFromPoint 遞迴定位最深層子視窗

     編輯:關於VC++

RealChildWindowFromPoint 僅搜尋直接子視窗,無法穿透重疊視窗定位最深層控制項。本文提供遞迴演算法:先定位最上層父視窗,再層層向下查找,實現 Spy++ 式的精準視窗拾取。

演算法邏輯

  1. WindowFromPoint 取得滑鼠座標下的最上層視窗 hWndTop。
  2. 向上追溯父視窗,直到頂層視窗(無父視窗、父為桌面、或非 WS_CHILD 樣式)作為搜尋根視窗 hRoot。
  3. ScreenToClient(hRoot, &pt) 轉換為根視窗用戶區座標。
  4. 迴圈呼叫 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 取得類別名等。範例程式實作「拖曳十字準星至目標視窗,顯示資訊並修改標題」功能,介面如圖二所示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved