Best method for storing this pointer for use in WndProc

前端 未结 10 813
南旧
南旧 2020-11-29 20:06

I\'m interested to know the best / common way of storing a this pointer for use in the WndProc. I know of several approaches, but each as I underst

10条回答
  •  醉梦人生
    2020-11-29 20:44

    I recommend setting a thread_local variable just before calling CreateWindow, and reading it in your WindowProc to find out the this variable (I presume you have control over WindowProc).

    This way you'll have the this/HWND association on the very first message sent to you window.

    With the other approaches suggested here chances are you'll miss on some messages: those sent before WM_CREATE / WM_NCCREATE / WM_GETMINMAXINFO.

    class Window
    {
        // ...
        static thread_local Window* _windowBeingCreated;
        static thread_local std::unordered_map _hwndMap;
        // ...
        HWND _hwnd;
        // ...
        // all error checking omitted
        // ...
        void Create (HWND parentHWnd, UINT nID, HINSTANCE hinstance)
        {
            // ...
            _windowBeingCreated = this;
            ::CreateWindow (YourWndClassName, L"", WS_CHILD | WS_VISIBLE, x, y, w, h, parentHWnd, (HMENU) nID, hinstance, NULL);
        }
    
        static LRESULT CALLBACK Window::WindowProcStatic (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
        {
            Window* _this;
            if (_windowBeingCreated != nullptr)
            {
                _hwndMap[hwnd] = _windowBeingCreated;
                _windowBeingCreated->_hwnd = hwnd;
                _this = _windowBeingCreated;
                windowBeingCreated = NULL;
            }
            else
            {
                auto existing = _hwndMap.find (hwnd);
                _this = existing->second;
            }
    
            return _this->WindowProc (msg, wparam, lparam);
        }
    
        LRESULT Window::WindowProc (UINT msg, WPARAM wparam, LPARAM lparam)
        {
            switch (msg)
            {
                // ....
    

提交回复
热议问题