how to set color for static control text in dialog?

27 08 2008


Colors convey meanings too. For instance, if something is written in red – that means something to be cautious. If its in green, its treated as safe. Well, usually in window dialogs, the static control texts are black in color. Is it possible to color them to convey more meaning?


Yes! You have to handle WM_CTLCOLOR message. For each control, this message will be triggered and you’re free to do modification on your control. Have a look at the code snippet in MFC framework.

// Message Map
BEGIN_MESSAGE_MAP(CDlgDlg, CDialog)
    ...
    ON_WM_CTLCOLOR()
END_MESSAGE_MAP()

HBRUSH CDlgDlg::OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor )
{
    // Call base class version at first. Or else it will override your changes.
    HBRUSH hbr = CDialog::OnCtlColor( pDC, pWnd, nCtlColor );

    // Check whether which static label its.
    if( pWnd->GetDlgCtrlID() == IDC_STATIC_OK )
    {
        // Set color as red.
        pDC->SetTextColor( RGB( 255, 0, 0 ));
        pDC->SetBkMode( TRANSPARENT );
    }

    return hbr;
}


Always call CDialog::OnCtlColor() at first. Or else it will override your modifications.


Targeted Audience – Intermediate.

Advertisements