我这样创建一个CStatic控件DlgStatic* newstatic;
newstatic = new DlgStatic();
newstatic->Create("Name",WS_CHILD|WS_VISIBLE|SS_NOTIFY|SS_SUNKEN,CRect(2,2,50,50),this,IDC_STATIC);
newstatic->ShowWindow(SW_SHOW); 其中DlgStatic是一个从CStatic派生来的类,类中有变量
COLORREF   m_clrFore;   //   foreground   color   
COLORREF   m_clrBack;   //background   color   
CBrush     m_brush;
构造函数中对变量初始化,onCtrlColor更改颜色DlgStatic::DlgStatic()
{
m_clrFore = RGB(255,255,0);  
    m_clrBack = RGB(192,192,192);
    m_brush.CreateSolidBrush(m_clrBack);
}
HBRUSH DlgStatic::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{
HBRUSH hbr = CStatic::OnCtlColor(pDC, pWnd, nCtlColor);

// TODO: Change any attributes of the DC here
if(pWnd->GetDlgCtrlID() == IDC_STATIC)
{
             pDC->SetTextColor(m_clrFore);
pDC->SetBkColor(m_clrBack);
return (HBRUSH)m_brush.GetSafeHandle();  
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
 
但是运行的时候控件的颜色还是默认的颜色,不知道这是什么错误

解决方案 »

  1.   

    HBRUSH DlgStatic::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
    {
        HBRUSH hbr = CStatic::OnCtlColor(pDC, pWnd, nCtlColor);
        
        // TODO: Change any attributes of the DC here
        if(pWnd->GetDlgCtrlID() == IDC_STATIC)
        {
                 pDC->SetTextColor(m_clrFore);
            pDC->SetBkColor(m_clrBack);
            return (HBRUSH)m_brush.GetSafeHandle();  
        }
        // TODO: Return a different brush if the default is not desired
        return hbr;
    }红色那个ID是默认ID,一般static都是用这个ID,也就是说你不能用这个ID作为唯一的ID来区分你的这个控件。自己自定义一个ID来代替ID_STATIC吧。
      

  2.   

    处理控件的反射消息 =WM_CTLCOLOR,而不是 WM_CTLCOLOR 。
      

  3.   

    BEGIN_MESSAGE_MAP(ClxStatic, CStatic)
       ON_WM_CTLCOLOR_REFLECT()
      END_MESSAGE_MAP()
      HBRUSH ClxStatic::CtlColor(CDC* pDC, UINT /*nCtlColor*/)
      {
       // TODO: Change any attributes of the DC here
       m_brushBack.Detach();
       m_brushBack.CreateSolidBrush(m_clrBack);
       pDC->SetBkColor(m_clrBack);
       pDC->SetTextColor(m_clrText);
       // TODO: Return a non-NULL brush if the parent's handler should not be called
       //return NULL;
       return (HBRUSH)m_brushBack.GetSafeHandle();
      }