现在的位置: 首页 > 综合 > 正文

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

2018年07月15日 ⁄ 综合 ⁄ 共 1889字 ⁄ 字号 评论关闭

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

 

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

 

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

 

以下是我的解决方法:

1. 从CStatic继承一个类CStaticEx(添加CStaticEx类,添加静态文本框的变量)

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

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

 // 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*/);  
};  

   

 

 // 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);  
}  

   转载:http://blog.163.com/pirates_fish/blog/static/18333315020111023354396/

抱歉!评论已关闭.