How to theme a button without glitching

90 Views Asked by At

I've been trying to theme a button in a Windows API application using C++. I want to make the button label red at all times. Currently I get only a red label until I move the window, after that I get a button with a red label as wanted. Sorry I'm not very experienced with the native Windows API (previously win32 API)

The code I've tried follows. I create the button

GetClientRect(hWnd, &rect);
hButton = CreateWindowExW(
    0L, 
    L"BUTTON",
    L"Hello, World!!!", 
    WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_FLAT,
    rect.right / 2 - 100,
    rect.bottom / 2 - 25,
    200, 
    50, 
    hWnd, 
    NULL, 
    ((LPCREATESTRUCT)lParam)->hInstance,
    NULL);

Then to theme it I use the following code in the WM_PAINT procedure of the Window Proc

 case WM_PAINT:
    {
        // Use DrawThemeBackground

        RECT rc;
        PAINTSTRUCT ps;
        GetClientRect(hButton, &rc);

        HDC hdc = GetDC(hWnd);

        HTHEME theme = OpenThemeData(hWnd, L"button");

        if (theme)
        {
            // Setup a DrawThemeTextEx Options struct
            DTTOPTS opts = { 0 };
            opts.dwSize = sizeof(opts);
            opts.crText = RGB(255, 0, 0);
            opts.dwFlags = DTT_TEXTCOLOR | DTT_COMPOSITED;

            WCHAR caption[255];
            GetWindowText(hButton, caption, 255);

            DrawThemeTextEx(theme, hdc, BP_PUSHBUTTON, CBS_UNCHECKEDNORMAL,
                caption, -1, DT_CENTER | DT_VCENTER | DT_SINGLELINE,
                &rc, &opts);
            CloseThemeData(theme);

        }
        else
        {
            // Draw the control without using visual styles.
        }

        ReleaseDC(hWnd, hdc);

        break;
    }

I wanted to ask if I'm doing something wrong or missing on something. I'd really appreciate.

0

There are 0 best solutions below