How do I avoid using global variables when using EnumWindows (or FindChildWindows) Win32 API?
I’ve approximately the following code:
HWND prog_hwnd;
BOOL CALLBACK ProgEnumProc(HWND hwnd, LPARAM lParam) {
if (...) {
// found the right hwnd, assign it to prog_hwnd;
prog_hwnd = hwnd;
return FALSE;
}
return TRUE;
}
void FindProgHwnd()
{
EnumWindows(ProgEnumProc, 0);
}
int main()
{
FindProgHwnd();
if (prog_hwnd) {
// found prog_hwnd, but it's global variable
}
}
As you can see, to find the right hwnd, I’ve to use a global variable prog_hwnd. I want to avoid using the global variable. Is there a way to do it?
Pass a pointer to the variable
(LPARAM)prog_hwndaslParam. This is then passed to the callback each time it is invoked.Within the callback you can assign to the passed variable by doing
*(HWND *)lParam = ....