MFC中可以设置字体颜色,背景色,前景色,是否透明

来源:互联网 发布:python 流量 预测 编辑:程序博客网 时间:2024/05/01 21:16
001////////////////////////////// label.h ////////////////////
002 
003#pragma once
004 
005 
006// Label
007 
008class Label : public CStatic
009{
010    DECLARE_DYNAMIC(Label)
011 
012public:
013    Label();
014    virtual ~Label();
015 
016protected:
017    DECLARE_MESSAGE_MAP()
018private:
019    CFont*  m_pFont;
020public:
021    CFont font;
022    COLORREF m_clrFont;                                     // 字体颜色
023    COLORREF m_clrBack;                                     // 背景颜色
024    BOOL m_bTransparent;                                    // 是否透明
025    afx_msg void OnPaint();
026    void SetFont(CString _strFontName, UINT _nFontSize);
027};
028 
029 
030 
031//////////////////////////////////////////////////////////////
032 
033 
034 
035 
036 
037////////////  label.cpp //////////////////
038 
039// Label.cpp : 实现文件
040//
041 
042#include "stdafx.h"
043#include "Label.h"
044 
045 
046// Label
047 
048IMPLEMENT_DYNAMIC(Label, CStatic)
049 
050Label::Label()
051: m_bTransparent(FALSE)
052{
053    int     nCount;
054    LOGFONT lf;
055    memset(&lf, 0, sizeof(LOGFONT));
056 
057    //设置字体样式
058    nCount  = sizeof(lf.lfFaceName)/sizeof(TCHAR);
059    _tcscpy_s(lf.lfFaceName, nCount, TEXT("宋体"));
060    lf.lfHeight  = 12;
061    lf.lfWeight  = 2;
062    lf.lfCharSet = GB2312_CHARSET;
063 
064    m_pFont = new CFont;
065    m_pFont->CreateFontIndirect(&lf);
066}
067 
068Label::~Label()
069{
070}
071 
072 
073BEGIN_MESSAGE_MAP(Label, CStatic)
074    ON_WM_PAINT()
075END_MESSAGE_MAP()
076 
077 
078 
079// Label 消息处理程序
080 
081 
082 
083void Label::OnPaint()
084{
085    CPaintDC dc(this);
086    RECT rect;
087    CString strCaption;
088     
089    GetWindowText(strCaption);
090    GetClientRect(&rect);
091    dc.SetTextColor(m_clrFont);
092 
093    if (m_bTransparent)
094    {
095        dc.SetBkMode(TRANSPARENT);
096    }
097    else
098    {
099        dc.SetBkColor(m_clrBack);
100    }
101 
102    dc.SelectObject(*m_pFont);
103    dc.DrawText(strCaption, &rect, DT_LEFT);
104}
105 
106void Label::SetFont(CString _strFontName, UINT _nFontSize)
107{
108    int     nCount;
109    LOGFONT lf;
110    memset(&lf, 0, sizeof(LOGFONT));
111 
112    //设置字体样式
113    nCount  = sizeof(lf.lfFaceName)/sizeof(TCHAR);
114    _tcscpy_s(lf.lfFaceName, nCount, _strFontName);
115    lf.lfHeight  = _nFontSize;
116    lf.lfWeight  = 2;
117    lf.lfCharSet = GB2312_CHARSET;
118 
119    delete m_pFont;
120    m_pFont = new CFont;
121    m_pFont->CreateFontIndirect(&lf);
122}