Dave's Brain

Browse - Programming Tips - How can I make a control that is static text with color?

Date: 2014apr15
Language: C++
Framework: MFC
OS: Windows

Q.  How can I make a control that is static text with color?

A.  Here is a class that does it.

--- ColorStatic.h ---

#ifndef COLORSTATIC_H #define COLORSTATIC_H // 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; } }; #endif
--- 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; }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.