通过非静态成员,无需外部设置 [英] Pass Non-Static Member without externally setting it
问题描述
我有两个类定义为:
class Control
{
private:
std::vector<int> Info;
public:
Control(..);
virtual ~Control();
LRESULT __stdcall SubClass(HWND Window, UINT Msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
};
class Button: public Control
{
//...
};
Control::Control(..)
{
SetWindowSubclass(..., SubClass, ...); //Need to pass member function as callback..
}
LRESULT __stdcall Control::SubClass(HWND Window, UINT Msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
//Use "Info" data member in here.. thus I cannot have static callback in order to use it.
}
所以我想出了:
class Control
{
private:
std::vector<int> Info;
static LRESULT __stdcall SetCallback(void* ThisPtr) {return static_cast<Control*>(ThisPtr)->SubClass;};
public:
//all the same stuff..
};
Control::Control(..)
{
SetWindowSubclass(..., SetCallback, ...);
}
但是上面的代码引发了一大堆错误。有没有反正要么有我的静态回调访问其他数据成员或有我的回调非静态?
我不想为每个创建的实例(我在互联网上看到的建议)做类似下面的事情:
But the above throws a whole bunch of errors. Is there anyway to either have my static callback access other datamembers OR have my callback non-static? I do not want to have to do something like the following for every instance created (which I've seen as suggestions all over the internet):
Control F;
F.SetCallback(&F::SubClass, &F); //Externally sets member as callback which I don't want.
我试图保留构造函数或类本身的一切。
I'm trying to keep everything in the constructor or the class itself.
推荐答案
这可能是最常见的问题,当涉及到Win32 API UI编程。请参阅:
This is probably the most common question when it comes to Win32 API UI programming. See:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff381400(v = vs.85).aspx
基本上,诀窍是调用SetWindowLongPtr,以GWLP_USERDATA作为第一个参数,以 this 作为第二个参数。然后在WindowProc回调中使用GetWindowLongPtr从HWND获取它。
Basically the trick is to call SetWindowLongPtr with GWLP_USERDATA as the first parameter and this as the second. Then in the WindowProc callback use GetWindowLongPtr to get it from the HWND.
这篇关于通过非静态成员,无需外部设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!