C++ GetWindowLong会丢失字段的数据
我为窗口做了一个包装,并希望从WndProc调用窗口方法。 为此,我将“this”指针传递给CreateWindwEx函数。 在WndProc中,我分配窗口类的hWnd字段,并通过SetWindowLongPtr存储它 但是,当我试图通过GetWindowLong读取它时,我得到了该窗口的断开实例(所有字段都有未定义的值),但是我可以调用w->foo()C++ GetWindowLong会丢失字段的数据,c++,winapi,C++,Winapi,我为窗口做了一个包装,并希望从WndProc调用窗口方法。 为此,我将“this”指针传递给CreateWindwEx函数。 在WndProc中,我分配窗口类的hWnd字段,并通过SetWindowLongPtr存储它 但是,当我试图通过GetWindowLong读取它时,我得到了该窗口的断开实例(所有字段都有未定义的值),但是我可以调用w->foo() 静态LRESULT回调WndProc(HWND-HWND,UINT消息,WPARAM-WPARAM,LPARAM-LPARAM) { 开关(信
静态LRESULT回调WndProc(HWND-HWND,UINT消息,WPARAM-WPARAM,LPARAM-LPARAM)
{
开关(信息)
{
案例WM\n创建:
{
LPCREATESTRUCT lpcs=reinterpret_cast(lpram);
Window*self=static_cast(lpcs->lpCreateParams);
//self->m_hInst和self->m_szWindowClass设置正确
//让我们设置hWnd
self->m_hWnd=hWnd;
SetWindowLongPtr(hWnd、GWLP_用户数据、重新解释_转换(自我));
返回true;
}
case WM_命令:
{
Window*w=reinterpret_cast(GetWindowLong(hWnd,GWLP_USERDATA));
//虽然“w”指针本身有效,但所有windows字段都已损坏
w->foo();
int wmId=低ORD(wParam);
//解析菜单选项:
交换机(wmId)
{
案例IDM_关于:
//对话框(m_hInst、MAKEINTRESOURCE(IDD_ABOUTBOX)、hWnd、About);
打破
案例IDM_退出:
窗口(hWnd);
打破
违约:
返回DefWindowProc(hWnd、message、wParam、lParam);
}
}
打破
案例WM_油漆:
{
Window*w=reinterpret_cast(GetWindowLong(hWnd,GWLP_USERDATA));
w->foo();
PAINTSTRUCT-ps;
HDC HDC=开始喷漆(hWnd和ps);
//TODO:在此处添加任何使用hdc的图形代码。。。
端漆(hWnd和ps);
}
打破
案例WM_销毁:
PostQuitMessage(0);
打破
违约:
返回DefWindowProc(hWnd、message、wParam、lParam);
}
返回0;
}
void foo()
{
//自动d=m_hInst;
自动s=m_hWnd;
}
我的错!
应使用GetWindowLongPtr而不是GetWindowLong
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_NCCREATE:
{
LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam);
Window* self = static_cast<Window*>(lpcs->lpCreateParams);
// self->m_hInst and self->m_szWindowClass are set properly
// lets set hWnd
self->m_hWnd = hWnd;
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LPARAM>(self));
return true;
}
case WM_COMMAND:
{
Window* w = reinterpret_cast<Window*>(GetWindowLong(hWnd, GWLP_USERDATA));
// got all the windows fields broken, though 'w' pointer itself is valid
w->foo();
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
//DialogBox(m_hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
Window* w = reinterpret_cast<Window*>(GetWindowLong(hWnd, GWLP_USERDATA));
w->foo();
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
void foo()
{
//auto d = m_hInst;
auto s = m_hWnd;
}