Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.

In my MFC application, i need to change the label color. The color will depend on the text to be displayed in the label.
Eg:- for Warning, a red text "Warning" need to be shown as label.
For Success, a green text "Success" need to be shown.

Please anybody help me?
Posted

1) You need specify ID different than IDC_STATIC for the label in question.
Here we used IDC_COLORED_LABEL in the sample code.

2a) MFC project

Add WM_CTLCOLOR handler for the dialog and modify it as follows:

HBRUSH CDialogDlg::OnCtlColor(CDC* pDC, CWnd* pWnd,
UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

// Add the following code
if (pWnd->GetDlgCtrlID() == IDC_COLORED_LABEL)
pDC->SetTextColor(RGB(128, 0, 0)); // dark red
// End

return hbr;
}


Note that MFC uses OnCtlColor method to handle all types of WM_CTLCOLORXXX
messages.

2b) Windows API

End the body of WM_CTLCOLORSTATIC dialog message handler with

return (BOOL) GetSysColorBrush(COLOR_3DFACE);

It is important that a valid brush handle, not TRUE or FALSE is returned.



HTH
 
Share this answer
 
will the OnCtlColor() get called , each time i need to change the label text?
How will i specify the required colour when i add text to the label?

in my code,
m_lStatusMessage.SetWindowText("Success");
m_lStatusMessage.SetFont(&m_Font); // i am increasing the font too.. this is working.
Here, how will i give RGB information?Or how can i call OnCtlColor()? can i directly call after the above two steps for changing the label color?
 
Share this answer
 
Comments
Sauro Viti 20-Jul-10 5:07am    
Please, don't post a comment as an answer; use the "Add comment" link below the answer instead
The WM_CTLCOLOR message is sent each time a control should be repainted, so you can add a COLORREF member to your dialog class and modify your code in a way similar to the snippet below:

In your class declaration:
C++
class CMyClass: public CDialog
{
   ...
protected:
   COLORREF m_rgbLabel;
   ...
};


In your class implementation:
C++
HBRUSH CDialogDlg::OnCtlColor(CDC* pDC, CWnd* pWnd,UINT nCtlColor)
{
   HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

   // Add the following code
   if (pWnd->GetDlgCtrlID() == IDC_COLORED_LABEL)
      pDC->SetTextColor(m_rgbLabel);

   return hbr;
}

...

   // Change the label color before changing its text!
   m_rgbLabel = RGB(0x00F, 0xFF, 0x00); // Light green
   m_lStatusMessage.SetWindowText("Success");
   m_lStatusMessage.SetFont(&m_Font);
 
...
 
Share this answer
 
Comments
reshmi2000 20-Jul-10 5:27am    
Thanks Viti.. it worked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900