MFC 对话框程序中无法使用CMFCStatusBar 对象(在VS2017环境下测试过),所以只能使用CStatusBar,但是CStatusBar无法设置文字颜色。
直接上图看效果:
定义CColorStatu继承CStatusBar ,在CColorStatu中重写两个函数,重写这个函数的目前的为了定值状态栏
void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
void SetPaneText(int nIndex, LPCTSTR lpszNewText, COLORREF crItemColor);
直接上源代码:
#ifndef COLORSTATU_H
#define COLORSTATU_H
#include "pch.h"
// ColorStatu.h : header file
//
//
/*自定义一个CColorStatu类继承CStatusBar
1.添加2个成员变量 Color和Text 目的是存放两个值 颜色和状态栏的文本
2.在构造函数中初始化2个变量
COLORREF Color;
CString Text ;
把它们初始化成数组的目的是为了存放多个值 (数组的大小于你的指示器数相关--你也可以重载SetIndicators函数来动态改变数组大小)
3.在CColorStatu中重写两个函数
重写这个函数的目前的为了定值状态栏---可查阅MSDN
void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
void SetPaneText(int nIndex, LPCTSTR lpszNewText, COLORREF crItemColor);
*
// CColorStatu window
class CColorStatu : public CStatusBar
{
// Construction
public:
CColorStatu();
public:
COLORREF Color; //定义一个指针变量存放字体颜色
CString Text;
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CColorStatu)
void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
void SetPaneText(int nIndex, LPCTSTR lpszNewText, COLORREF crItemColor);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CColorStatu();
// Generated message map functions
protected:
//{{AFX_MSG(CColorStatu)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif
// ColorStatu.cpp : implementation file
//
#include "pch.h"
#include "ColorStatu.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CColorStatu
CColorStatu::CColorStatu()
{
Color= COLORREF(RGB(0,0,0)); //new一个数组赋给这个指针 那么指针现在就指向拥有4个颜色的数组
}
CColorStatu::~CColorStatu()
{
//释放内存
}
BEGIN_MESSAGE_MAP(CColorStatu, CStatusBar)
//{{AFX_MSG_MAP(CColorStatu)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/
// CColorStatu message handlers
void CColorStatu::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
//DRAWITEMSTRUCT 为需要自绘的控件或者菜单项提供了必要的信息
//获取ID
UINT unID= lpDrawItemStruct->itemID;
CDC dc;
//hDC附加到CDC对象
dc.Attach(lpDrawItemStruct->hDC);
//设置设备上下文对象的背景模式为
dc.SetBkMode(TRANSPARENT);
//dc.SetBkColor(RGB(0, 255, 0));设置文字区域背景颜色
//lpDrawItemStruct->rcItem指定了将被绘制的矩形区域
//创建一个矩形区域
CRect rect(&lpDrawItemStruct->rcItem);
//设置颜色 Color[unID]--根据ID传值设置颜色
dc.SetTextColor(Color);
//输出 Text[unID]根据ID传值设置文本
dc.TextOut(rect.left+1, rect.top,Text);
//分离DC
dc.Detach();
}
void CColorStatu::SetPaneText(int nIndex, LPCTSTR lpszNewText, COLORREF crItemColor)
{
//给数组赋值
Text = lpszNewText;
Color= crItemColor;
//在一个状态条控件的给定部分中设置文本 SBT_OWNERDRAW| SBT_NOBORDERS -组合使用没有3D外观
GetStatusBarCtrl().SetText(L"", nIndex,SBT_OWNERDRAW| SBT_NOBORDERS);
}