tags:

views:

1493

answers:

2

Hi All,

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

thanks...

+3  A: 

Hi Owen,

unfortunately you won't find a SetTextColor method in the CStatic class. If you want to change the text color of a CStatic you will have to code a bit more.

In my opinion the best way is creating your own CStatic-derived class (CMyStatic) and there cacth the ON_WM_CTLCOLOR_REFLECT notification message.

BEGIN_MESSAGE_MAP(CMyStatic, CStatic)
    //{{AFX_MSG_MAP(CMyStatic)
    ON_WM_CTLCOLOR_REFLECT()
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

HBRUSH CColorStatic::CtlColor(CDC* pDC, UINT nCtlColor) 
{
    pDC->SetTextColor(RGB(255,0,0)); 

    return (HBRUSH)GetStockObject(NULL_BRUSH); 
}

Obviously you can use a member variable and a setter method to replace the red color (RGB(255,0,0)).

Regards.

Javier De Pedro
+5  A: 

@Javier's answer is a good one, but you can also 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.

djeidot
You are right. This is another way to do it. I just mentioned the way I think is better. In this second case you have to add the code to every dialog you want to display the labels in other color.
Javier De Pedro
Yes, I agree, in this case your way is the better way. My way could be used if someone wants to do a major revamping in the entire dialog (or application).
djeidot
The return (HBRUSH)GetStockObject(NULL_BRUSH); will cause a painting issue (or a funky transparent background 'feature'). You probably want to return (HBRUSH)GetStockObject(WHITE_BRUSH);
Jack Bolding