bodacydo
bodacydo

Reputation: 79539

How do I avoid using a global variable when doing `EnumWindows` to find a windows in Win32 C API?

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?

Upvotes: 3

Views: 919

Answers (1)

Mike Kwan
Mike Kwan

Reputation: 24477

Pass a pointer to the variable (LPARAM)prog_hwnd as lParam. 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 = ....

Upvotes: 7

Related Questions