how can I set static controls background color programmatically

前端 未结 1 574
-上瘾入骨i
-上瘾入骨i 2021-01-26 17:23

I want to change label background color within a function, I tried this code but nothing changed after calling changecolor function

HWND hWndLabel;
         


        
1条回答
  •  清酒与你
    2021-01-26 18:02

    Try something more like this:

    HWND hWndLabel;
    HBRUSH hBrushLabel;
    COLORREF clrLabelText;
    COLORREF clrLabelBkGnd;
    
    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
        switch (message)
        {
        case WM_CREATE:
            hWndLabel = CreateWindowEx(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE | SS_LEFT,
                75, 75, 70, 70, hWnd, (HMENU)labelId, hInst, NULL);
            hBrushLabel = NULL;
            clrLabelText = GetSysColor(COLOR_WINDOWTEXT);
            clrLabelBkGnd = GetSysColor(COLOR_WINDOW);
            break;
    
        case WM_DESTROY:
            if (hBrushLabel) DeleteObject(hBrushLabel);
            PostQuitMessage(0);
            break;
    
        case WM_CTLCOLORSTATIC: {
            HDC hdc = reinterpret_cast(wParam);
            SetTextColor(hdc, clrLabelText);
            SetBkColor(hdc, clrLabelBkGnd);
            if (!hBrushLabel) hBrushLabel = CreateSolidBrush(clrLabelBkGnd);
            return reinterpret_cast(hBrushLabel);
        }
    
        case WM_COMMAND:  // all events are handled here
            break;
    
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
            break;
        }
        return 0;
    }
    
    DWORD WINAPI changecolor()
    {
        if (hBrushLabel) {
            DeleteObject(hBrushLabel);
            hBrushLabel = NULL;
        }
        clrLabelText = RGB(0xFF, 0x00, 0x00);
        clrLabelBkGnd = RGB(0, 0, 230);
        InvalidateRect(hWndLabel, NULL, TRUE);
        return 0;
    }
    

    There is a similar example in the WM_CTLCOLORSTATIC documentation.

    The following C++ example shows how to set the text foreground and background colors of a static control in response to the WM_CTLCOLORSTATIC message. The hbrBkgnd variable is a static HBRUSH variable that is initialized to NULL, and stores the background brush between calls to WM_CTLCOLORSTATIC. The brush must be destroyed by a call to the DeleteObject function when it is no longer needed, typically when the associated dialog box is destroyed.

    case WM_CTLCOLORSTATIC:
        {
        HDC hdcStatic = (HDC) wParam;
        SetTextColor(hdcStatic, RGB(255,255,255));
        SetBkColor(hdcStatic, RGB(0,0,0));
    
        if (hbrBkgnd == NULL)
        {
            hbrBkgnd = CreateSolidBrush(RGB(0,0,0));
        }
        return (INT_PTR)hbrBkgnd;
        }
    

    0 讨论(0)
提交回复
热议问题