Not receiving pointer after calling GetWindowLongPtr with GWLP_USERDATA

Viewed 75

I have a Window procedure which I have defined in a class and I need to be able to access the class' members using the this pointer.

The Window procedure:

static LRESULT CALLBACK TextWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    MyCustomClass* self = 
        reinterpret_cast<MyCustomClass*>(
            GetWindowLongPtr(hWnd, GWLP_USERDATA)  // Not recieving the pointer!
        );
 


    switch(message) {
        case WM_DESTROY: {
            SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)self->origWndProc); // I am subclassing btw.
            break;
        }

        case WM_PAINT: {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);

            HBRUSH hBrush = (HBRUSH)GetStockObject(NULL_BRUSH);
            FillRect(hdc, &ps.rcPaint, hBrush);

            SetBkMode(hdc, TRANSPARENT);
            DrawText(hdc, L"OK", -1, &ps.rcPaint, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
            SetBkMode(hdc, OPAQUE);

            EndPaint(hWnd, &ps);
            DeleteObject(hBrush);
            break;
        }

        case WM_LBUTTONDOWN: {
            printf("%d", self->x); // Crashes the program
            break;
        }
    }
    return CallWindowProc(self->origWndProc, hWnd, message, wParam, lParam); // Subclassing!
}

Now after creating the window (a text control in my case) I am immediately setting the pointer to the class using SetWindowLongPtr, like this:

// Variable in the class that holds the `HWND` data to the text control.
this->textControl = CreateWindow(
    L"STATIC",
    L"Hello World!",
    WS_CHILD | WS_VISIBLE | SS_NOTIFY,
    this->x, this->y, this->width, this->height, // Position and size, members defined in the class
    this->parentWindow, // Parent window.
    0, 
    NULL,
    NULL
);

SetWindowLongPtr(this->textControl, GWLP_USERDATA, (LONG_PTR)this); // Setting the pointer
this->origWndProc = (WNDPROC)SetWindowLongPtr(this->textControl, GWLP_WNDPROC, (LONG_PTR)this->TextWndProc); // Setting the window procedure for "Subclassing"!

But the problem is I am not receiving the this pointer when I am calling GetWindowLongPtr as seen in the Window procedure.

Am I calling it wrong? I don't know what is wrong.

Any help would be greatly appreciated! Thank you in advance!

0 Answers
Related