MFC - change text color of a cstatic text control

Owen picture Owen · Oct 28, 2009 · Viewed 60.2k times · Source

How do you change the text color of a CStatic text control? Is there a simple way other that using the CDC::SetTextColor?

thanks...

Answer

djeidot picture djeidot · Oct 29, 2009

You can implement ON_WM_CTLCOLOR in your dialog class, without having to create a new CStatic-derived class:

BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
    //{{AFX_MSG_MAP(CMyDialog)
    ON_WM_CTLCOLOR()
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd *pWnd, UINT nCtlColor)
{
    switch (nCtlColor)
    {
    case CTLCOLOR_STATIC:
        pDC->SetTextColor(RGB(255, 0, 0));
        return (HBRUSH)GetStockObject(NULL_BRUSH);
    default:
        return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
    }
}

Notice that the code above sets the text of all static controls in the dialog. But you can use the pWnd variable to filter the controls you want.