我想使用这个函数“EnumWindows(EnumWindowsProc, NULL);”。 EnumWindowsProc 是一个回调函数:
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
对于这个回调,我想使用一个类的成员函数。
例如:
Class MyClass
{
BOOL CALLBACK My_EnumWindowsProc(HWND hwnd, LPARAM lParam);
void test();
};
所以我想将调用的回调与我的函数绑定(bind)!!!
我试试这个:
void MyClass::test()
{
EnumWindowsProc ptrFunc = mem_fun(&MyClass::My_EnumWindowsProc);
EnumWindows(ptrFunc, NULL);
}
这是行不通的,“mem_fun”只能接受一个参数! 有可能这样做吗?否则你知道另一种解决方案吗? (也许 Boost::bind 可以解决这个问题)
最佳答案
您需要创建一个 Adapter ,例如:
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class MyCallback
{
public:
MyCallback() : count_(0) {};
static BOOL CALLBACK CallbackAdapter(HWND, LPARAM);
BOOL Callback(HWND);
unsigned count_;
};
BOOL MyCallback::Callback(HWND wnd)
{
char title[1025] = {};
GetWindowText(wnd, title, sizeof(title)-1);
cout << wnd << "= '" << title << "'" << endl;
++count_;
return TRUE;
}
BOOL MyCallback::CallbackAdapter(HWND wnd, LPARAM lp)
{
MyCallback* that = reinterpret_cast<MyCallback*>(lp);
return that->Callback(wnd);
}
int main()
{
MyCallback cb;
EnumWindows(&MyCallback::CallbackAdapter, reinterpret_cast<LPARAM>(&cb));
cout << "Windows Found: " << cb.count_;
return 0;
}
关于c++ - 如何使用两个参数获得 memfun,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2381719/