Date: 2014apr15
Updated: 2014sep17
Language: C++
Framework: MFC
OS: Windows
Q. MFC: Make a control that is static text with color
A. Here is a class that does it.
--- ColorStatic.h ---
#pragma once
// Looks good with vertical and horiztonal centering turned on
class CColorStatic : public CStatic
{
COLORREF m_bgColor;
COLORREF m_txtColor;
public:
CColorStatic();
//{{AFX_MSG(CColorStatic)
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
public:
void SetBgColor(const COLORREF c)
{
m_bgColor = c;
}
void SetTextColor(const COLORREF c)
{
m_txtColor = c;
}
void SetColor(const COLORREF bg, const COLORREF txt)
{
m_bgColor = bg;
m_txtColor = txt;
}
};
--- ColorStatic.cpp ---
#include "stdafx.h"
#include "ColorStatic.h"
BEGIN_MESSAGE_MAP(CColorStatic, CStatic)
//{{AFX_MSG_MAP(CColorStatic)
ON_WM_CTLCOLOR_REFLECT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CColorStatic::CColorStatic()
{
m_bgColor = RGB(0xff, 0xff, 0xff); // white
m_txtColor = RGB(0x00, 0x00, 0x00); // black
}
HBRUSH CColorStatic::CtlColor(CDC* pDC, UINT nCtlColor)
{
HBRUSH hbr = NULL;
CRect rect;
if (pDC == NULL) return hbr;
// Background
CBrush brush = m_bgColor;
CBrush* pOldBrush = pDC->SelectObject(&brush);
GetClientRect(rect);
pDC->Rectangle(rect);
// Text
pDC->SetTextColor(m_txtColor);
pDC->SetBkMode(TRANSPARENT);
hbr = (HBRUSH)::GetStockObject(HOLLOW_BRUSH);
return hbr;
}