C ++ Win32更改静态颜色

时间:2017-08-12 17:28:17

标签: c++ windows winapi

我想创建标签并更改其背景颜色和文字颜色

我用这个

HWND hwnder = CreateWindow(TEXT("static"), TEXT(text), WS_VISIBLE | WS_CHILD | SS_LEFT, 10, 10, 50, 60, hwnd, (HMENU) NULL, NULL, NULL);
HDC hdcStatic = GetDC(hwnder);
SetTextColor(hdcStatic, RGB(12,34,210));
SetBkColor(hdcStatic, RGB(12,34,210));

标签是否已创建,但其颜色没有改变,有什么办法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

处理WndProc功能中的WM_CTLCOLORSTATIC消息:

case WM_CTLCOLORSTATIC:
{
    HDC hdcStatic = (HDC)wParam; // or obtain the static handle in some other way
    SetTextColor(hdcStatic, RGB(255, 0, 0)); // text color
    SetBkColor(hdcStatic, RGB(12,34,210));
    return (LRESULT)GetStockObject(NULL_BRUSH);
}
break;

如果您只想更改特定组件的颜色,请使用简单的if语句获取目标的句柄:

case WM_CTLCOLORSTATIC:
{
    if (GetDlgCtrlID((HWND)lParam) == IDC_STATIC1) // Target the specific component
    {
        // same as above
    }
}
break;