还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

MFC Static透明背景色的实现、Static控件自绘、Static字体修改

来源:清泛原创     2016-11-01 10:39:45    人气:     我有话说( 0 人参与)

第一种:pDC->SetBkMode(TRANSPARENT);afx_msg HBRUSH CtlColor(CDC* *pDC* , UINT *nCtlColor* );COLORREF m_crText;COLORREF m_...

第一种:pDC->SetBkMode(TRANSPARENT);
afx_msg HBRUSH CtlColor(CDC* /*pDC*/, UINT /*nCtlColor*/);
COLORREF m_crText;
COLORREF m_crBk;
HBRUSH m_hbkbr;
...
BEGIN_MESSAGE_MAP(CTransparentStatic, CStatic)
	ON_WM_CTLCOLOR_REFLECT()
END_MESSAGE_MAP()

CTransparentStatic::CTransparentStatic()
{
	m_crText = RGB(40, 40, 40);
	m_crBk = RGB(255,255,255);
	m_hbkbr = CreateSolidBrush(m_crBk);
}
...
HBRUSH CTransparentStatic::CtlColor(CDC* pDC, UINT nCtlColor)
{
	pDC->SetBkMode(TRANSPARENT);  //关键起作用的在这句
	HBRUSH hb = (HBRUSH)GetStockObject(NULL_BRUSH);
	if(CTLCOLOR_STATIC == nCtlColor)   
	{     
		pDC->SetTextColor(m_crText);
		pDC->SetBkColor(m_crBk);
		hb = m_hbkbr;
	}   

	return hb;
}
这种方式比较简单,仅仅需要背景色透明的话采用这种较为方便。


第二种:重载DrawItem函数进行自绘,将背景设置成窗口的背景色
virtual void PreSubclassWindow();
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);

...
//添加Owner Draw属性
void CTransparentStatic::PreSubclassWindow() 
{
	// TODO: Add your specialized code here and/or call the base class
	
	CStatic::PreSubclassWindow();
	DWORD dwStyle = GetStyle();  
	SetWindowLong(GetSafeHwnd(),GWL_STYLE,dwStyle | SS_OWNERDRAW);
}

void CTransparentStatic::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
	int nSaveDC = pDC->SaveDC();

	pDC->SetBkMode(TRANSPARENT);
	// 取得位置
	CRect client_rect;
	GetClientRect(client_rect);

	// 取得文本
	CString szText;
	GetWindowText(szText);

	// 取得字体,并选入设备文件
	CFont *pFont, *pOldFont;
	pFont = ::GetFont(_T("微软雅黑"), 10);
	pOldFont = pDC->SelectObject(pFont);

	pDC->TextOut(0, 0, szText);

	pDC->SelectObject(pOldFont);
	pDC->RestoreDC(nSaveDC);
}
这种采用完全自绘的方式更为灵活,可以改变字体、文本颜色等。
自绘时注意点:
1、消息映射中不要有:ON_WM_PAINT、ON_WM_DRAWITEM 消息,否则DrawItem函数不会被调用。
2、DrawItem而非OnDrawItem。OnDrawItem是ON_WM_DRAWITEM消息的处理函数,是处理子控件发送过来的自绘消息的。

MFC Static 自绘 CtlColor

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: