注意: 使用Lambda表达式会增加额外开销,但却有时候又蛮方便的。
Windows下查找子孙窗口实例:
HWND FindDescendantWindows(HWND hWndParent, LPCTSTR lpClassName, LPCTSTR lpWindowName)
{
HWND hFind = nullptr;
UINT nCompare = 0;
nCompare += (lpClassName != nullptr) ? 1 : 0;
nCompare += (lpWindowName != nullptr) ? 1 : 0;
if (nCompare == 0)
return nullptr;
TCHAR szClass[MAX_CLASS_NAME];
TCHAR szTitle[MAX_PATH];
std::function< HWND(HWND hWndParent, LPCTSTR lpClassName, LPCTSTR lpWindowName)> _FindDescendantWindows;
_FindDescendantWindows = [&](HWND hWndParent, LPCTSTR lpClassName, LPCTSTR lpWindowName)->HWND {
HWND hChild = ::GetWindow(hWndParent, GW_CHILD);
while (hChild != NULL)
{
UINT cmp = 0;
::GetClassName(hChild, szClass, MAX_CLASS_NAME);
if (_tcsicmp(szClass, lpClassName) == 0)
cmp++;
if (cmp == nCompare)
return hChild;
::GetWindowText(hChild, szTitle, MAX_PATH);
if (_tcsicmp(szTitle, lpWindowName) == 0)
cmp++;
if (cmp == nCompare)
return hChild;
HWND hFind = _FindDescendantWindows(hChild, lpClassName, lpWindowName);
if (hFind != nullptr)
return hFind;
hChild = ::GetWindow(hChild, GW_HWNDNEXT);
}
return nullptr;
};
return _FindDescendantWindows(hWndParent, lpClassName, lpWindowName);
}