Lambda 表达式递归用法实例

时间:2023-03-09 21:31:46
Lambda 表达式递归用法实例

注意: 使用Lambda表达式会增加额外开销,但却有时候又蛮方便的。

Windows下查找子孙窗口实例:

HWND FindDescendantWindows(HWND hWndParent, LPCTSTR lpClassName, LPCTSTR lpWindowName)
{
HWND hFind = nullptr; UINT nCompare = ;
nCompare += (lpClassName != nullptr) ? : ;
nCompare += (lpWindowName != nullptr) ? : ; if (nCompare == )
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 = ;
::GetClassName(hChild, szClass, MAX_CLASS_NAME);
if (_tcsicmp(szClass, lpClassName) == )
cmp++;
if (cmp == nCompare)
return hChild; ::GetWindowText(hChild, szTitle, MAX_PATH);
if (_tcsicmp(szTitle, lpWindowName) == )
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);
}