Resort to thunks or tls? I dont know what you mean by a thunk in this case, but its quite easy - if just a little convoluted - to bootstrap a window into a c++ class wrapper.
class UserWindow
{
HWND _hwnd;
public:
operator HWND(){
return _hwnd;
}
UserWindow():_hwnd(0){}
~UserWindow(){
if(_hwnd){
SetWindowLongPtr(GWL_USERDATA,0);
DestroyWindow(_hwnd);
}
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
UserWindow* self = 0;
if(uMsg == WM_CREATE)
{
LPCREATESTRUCT crst = (LPCREATESTRUCT)lParam;
self = (Window*)crst->lpCreateParams;
SetWindowLongPtr(hwnd,GWL_USERDATA,(LONG_PTR)self);
self->_hwnd = hwnd;
}
else
self = (Window*)GetWindowLongPtr(hwnd,GWL_USERDATA);
if(self){
LRESULT lr = self->WndProc(uMsg,wParam,lParam);
if(uMsg == WM_DESTROY){
if(self = (Window*)GetWindowLongPtr(hwnd,GWL_USERDATA))
self->_hwnd = NULL;
}
return lr;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
HWND Create(int x, int y, int w, int h, LPCTSTR pszTitle,DWORD dwStyle,DWORD dwStyleEx,LPCTSTR pszMenu,HINSTANCE hInstance, HWND hwndParent){
WNDCLASSEX wcex = { sizeof (wcex),0};
if(!GetClassInfo(hInstance,ClassName(),&wcex)){
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WindowndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.lpszClassName = ClassName();
OnCreatingClass( wcex );
RegisterClassEx(&wcex);
}
return CreateWindowEx( dwStyleEx, ClassName(), pszTitle, dwStyle, x, y, w, h, hwndParent, pszMenu, hInstance, this);
}
// Functions to override
virtual LPCTSTR ClassName(){
return TEXT("USERWINDOW");
}
virtual LRESULT WindowProc(UINT uMsg, WPARAM wParam,LPARAM lParam){
return DefWindowProc(uMsg,wParam,lParam);
}
virtual void Window::OnCreatingClass(WNDCLASSEX& wcex){
wcex.hCursor = LoadCursor(NULL,IDC_ARROW);
}
};
It is all a bit convoluted, but it means that the window can be destroyed safely by deleting the class, OR by being destroyed. There are one or two sizing related messages sent during the call to CreateWindow before WM_CREATE sets GWL_USERDATA to "this" but practically they are of no consequence. The window class is automatically created the first time the window is instantiated.
One thing this style of automatic class registration on the first call to create does not support is the instantiation of this type of window as a control on a dialog - To support that case a whole slew of things would need to be changed... provide a static class registration function... a "new MyClass" in the static WM_CREATE handler... its not obvious to me how this could be done in a frameworkish type fashion.