【问题标题】:GetWindowLong loses data of fieldsGetWindowLong 丢失字段数据
【发布时间】:2020-11-01 12:18:05
【问题描述】:

我为 Window 做了一个包装器,并想从 WndProc 调用窗口方法。 为此,我将“this”指针传递给 CreateWindwEx 函数。 在 WndProc 我分配 Window 类的 hWnd 字段并通过 SetWindowLongPtr 存储它 但是当我尝试通过 GetWindowLong 读取它时,我得到了窗口的损坏实例(所有字段都有未定义的值),但是我可以调用 w->foo()

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;
    }

【问题讨论】:

    标签: c++ winapi


    【解决方案1】:

    我的错! 应使用 GetWindowLongPtr 代替 GetWindowLong

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 2018-06-22
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多