1

I used the following overloaded method to change the text color to red in a listbox, in a Visual C++ MFC dialog based application. When I build the program in DEBUG mode, it works perfectly. But when I use the RELEASE mode the text color doesn't change. Why is this and how can I overcome this problem??

Thanks!!

HBRUSH MyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
  if(nCtlColor == CTLCOLOR_LISTBOX)
  {
     if(bChangeTextColor)
     {
       pDC->SetTextColor(RGB(255, 0, 0));
       return m_hRedBrush;
     }
  } 
  return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}
sharptooth
  • 167,383
  • 100
  • 513
  • 979
Isuru
  • 182
  • 1
  • 2
  • 11

3 Answers3

9

You must declare in MESSAGE_MAP

ex:

BEGIN_MESSAGE_MAP(CTrainMFCDlg, CDialog)
    ON_WM_SYSCOMMAND()    
    ON_WM_PAINT()    
    ON_WM_QUERYDRAGICON()    
    //}}AFX_MSG_MAP

    ON_WM_CTLCOLOR()  // your handle    
END_MESSAGE_MAP()
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
trongtien
  • 91
  • 1
  • 1
3

Can you try to call the base implementation CDialog::OnCtlColor before your custom code, like this:

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

    if(nCtlColor == CTLCOLOR_LISTBOX)
    {
        if(bChangeTextColor)
        {
            pDC->SetTextColor(RGB(255, 0, 0));
            hBrush=m_hRedBrush;
        }
    } 
    return hBrush;
}

CDialog::OnCtlColor does some stuff internally which is skipped by your return inside of your function. It's only a very vague idea but I have always used OnCtlColor this way and never had a problem.

Slauma
  • 175,098
  • 59
  • 401
  • 420
0

I have to use both previous answers to make it work.

  1. I declared handle in MESSAGE_MAP

    BEGIN_MESSAGE_MAP(CTrainMFCDlg, CDialog)
    
        ON_WM_CTLCOLOR()  // your handle
    
    END_MESSAGE_MAP()
    
  2. I used CDialog::OnCtlColor before my custom code:

    HBRUSH MyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
    {
         HBRUSH hBrush=CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
    
         if(nCtlColor == CTLCOLOR_LISTBOX)
         {
              if(bChangeTextColor)
              {
                   pDC->SetTextColor(RGB(255, 0, 0));
                   hBrush=m_hRedBrush;
              }
        } 
        return hBrush;
    }
    
tjeden
  • 2,019
  • 1
  • 13
  • 19