4

Can I use member function as first argument to EnumWindows? I don't see any workaround in this case even with boost::bind.

hmjd
  • 120,187
  • 20
  • 207
  • 252
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

2 Answers2

7

Given this normal callback function:

BOOL CALLBACK EnumWindowsProc(HWND wnd, LPARAM lParam);

You can invoke EnumWindows using lParam to pass it a pointer to your class:

EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(this));

In EnumWindowsProc you can simply call member function (casting lParam to your class type). Like this:

BOOL CALLBACK EnumWindowsProc(HWND wnd, LPARAM lParam)
{
    return reinterpret_cast<MyClass*>(lParam)->EnumWindows(wnd);
}

If you don't want to make your class method public you can:

  • Pack a struct to contain both class instance and pointer to member.
  • Use a library for delegates.
  • Use boost std:bind (in this case it'll work well because you do it on your own class member, it has not to be __stdcall).

Whatever you will use you can find more details in this post here on SO.

Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
3

EnumWindows takes a callback that looks like this

BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam);

You cannot use either a member function or a lambda that has a capture. You do this instead.

typedef std::function<bool(HWND hwnd)> func_type;
BOOL CALLBACK MyEnumProc(HWND hwnd, LPARAM lparam)
{
    auto& func = *reinterpret_cast<func_type*>(lparam);
    if(func(hwnd))return TRUE;
    else return FALSE;

}

You would use it like this

auto f = std::make_shared<func_type>(std::bind(&mymemberfunction,this));
EnumWindows(MyEnumProc,reinterpret_cast<LPARAM>(f.get()));

//Make sure to keep the shared_ptr around until you are done enumerating
John Bandela
  • 2,416
  • 12
  • 19