MFC中设置静态文本的字体颜色、背景透明以及解决字体重叠

原创:qsycnhttp://blog.csdn.net/qsycn/article/details/5999288

 

改变static的颜色和设为背景透明可以在父窗口的WM_CTLCOLOR中实现(即HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor))

将static设为背景透明时,改变该控件的文本将会出现文字重叠的现象。

 

其实设置为透明背景也就是在static重画背景时返回一个空的刷子而已,所以你改变文本并没有改变上次残留的背景,从而导致重叠现象。

为了解决这个问题,我们可以让父窗口重绘此区域。

 

以下是我的解决方法:

1. 从CStatic继承一个类CStaticEx

2. 增加WM_CTLCOLOR的消息反射(把很多事情留给父窗口处理并不是一件推荐的事,就让CStaticEx自己处理这件事,这样还可以不影响到其它的static)

3. 处理WM_SETTEXT,当文本改变时,重绘父窗口的该控件所在区域

 

 

// StaticEx.cpp : implementation file
//

#include "stdafx.h"
#include "StaticEx.h"


// CStaticEx

IMPLEMENT_DYNAMIC(CStaticEx, CStatic)

CStaticEx::CStaticEx()
{

}

CStaticEx::~CStaticEx()
{
}


BEGIN_MESSAGE_MAP(CStaticEx, CStatic)
 ON_WM_CTLCOLOR_REFLECT()
END_MESSAGE_MAP()



// CStaticEx message handlers



HBRUSH CStaticEx::CtlColor(CDC* pDC, UINT /*nCtlColor*/)
{
 // TODO:  Change any attributes of the DC here
 pDC->SetTextColor(RGB(255, 0, 0));//设置文字的颜色   
    pDC->SetBkMode(TRANSPARENT);//透明   
    return (HBRUSH)::GetStockObject(NULL_BRUSH);

 // TODO:  Return a non-NULL brush if the parent's handler should not be called
 //return NULL;
}

LRESULT CStaticEx::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
 // TODO: Add your specialized code here and/or call the base class
 if(message==WM_SETTEXT) {
  CRect rect;
  GetWindowRect(&rect);
  CWnd* pParent = GetParent();
  if(pParent) {
   pParent->ScreenToClient(&rect);
   pParent->InvalidateRect(&rect);
  }
 }

 return CStatic::DefWindowProc(message, wParam, lParam);
}

  

// StaticEx.h : header file
//

#pragma once


// CStaticEx

class CStaticEx : public CStatic
{
	DECLARE_DYNAMIC(CStaticEx)

public:
	CStaticEx();
	virtual ~CStaticEx();

protected:
	virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);

protected:
	DECLARE_MESSAGE_MAP()
	afx_msg HBRUSH CtlColor(CDC* pDC, UINT /*nCtlColor*/);
};

  

posted @ 2011-12-01 13:00  refazy  阅读(5134)  评论(1编辑  收藏  举报