原文链接: http://blog.sina.com.cn/s/blog_4a470fcc01000406.html
这篇文章中有些许错误,不过思路值得借鉴
如果在一个有颜色的窗体中创建一个CStatic的对象X,而且该X要改变它的文本内容,那么就有一个X背景是默认窗体背景的问题,而不是那个颜色窗体的背景,这是因为,在SetWindowText时会OnEraseBkgnd擦除X原来的界面的背景,然后调用默认的Onpaint画上window默认的窗体颜色。
解决办法有两个:
方法1
接受ON_WM_CTLCOLOR消息,该消息拦截了画窗体以及窗体上控件的背景颜色的操作
实现如下:
HBRUSH CRDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
//CTLCOLOR_STATIC为 CStatic
//CTLCOLOR_EDIT
//CTLCOLOR_LISTBOX
//CTLCOLOR_BTN
//CTLCOLOR_DLG 等等
if ( nCtlColor == CTLCOLOR_STATIC )
{
static HBRUSH hbrStatic = ::CreateSolidBrush(RGB(255, 0, 255));
//COLOR是你想设置的背景颜色 此处必须为静态变量,否则不能实现
pDC->SetBkColor(RGB(255, 0, 255));
return hbrStatic ; //返回该刷
}
return hbr;
}
方法2
思路是:创建一个CSatic的类CStaticEx、, 包含一个CDC的成员m_memDC,把窗体的背景作为m_memDC的初始化,在CStaticEx的OnEraseBkgnd内BitBlt m_memDC则,这是X的背景为窗体的背景了
// 在OnPaint内初始化m_memDC
void CStaticEx::OnPaint()
{
static BOOL bFirst = TRUE;
CFont font;
VERIFY(font.CreateFont(
15, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
FW_NORMAL, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
DEFAULT_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily
“Arial”)); // lpszFacename
CPaintDC dc(this); // device context for painting
CRect rcStatic, rcParent;
GetWindowRect(&rcStatic);
if(bFirst)//这里把父窗口所画的保存起来
{
CRect rcStaticInParent;
bFirst = FALSE;
CWnd* pParent = GetParent();
rcStaticInParent = rcStatic;
pParent->ScreenToClient(&rcStaticInParent);
CDC* pParentDC = pParent->GetDC();
m_memBp.CreateCompatibleBitmap(&dc, rcStaticInParent.Width(), rcStaticInParent.Height());
m_memDC.CreateCompatibleDC(&dc);
m_memDC.SelectObject(m_memBp.GetSafeHandle());
SYS_DEBUG_OUT(Output_Console,”rcStaticInParent.left=%d; rcStaticInParent.top=%d; rc.bottom=%d;rc.right=%d”,rcStaticInParent.left,rcStaticInParent.top,rcStaticInParent.bottom, rcStaticInParent.right);
m_memDC.StretchBlt(0, 0, rcStaticInParent.Width(), rcStaticInParent.Height(), pParentDC, rcStaticInParent.left, rcStaticInParent.top, rcStaticInParent.Width(), rcStaticInParent.Height(),SRCCOPY);
GetParent()->ReleaseDC(pParentDC);
}
// 写CStatic文本
CString strWinText;
GetWindowText(strWinText);
dc.SelectObject(&font);
dc.SetTextColor(RGB(255,255,255));
dc.SetBkMode(TRANSPARENT);
dc.TextOut(0,0,strWinText);
}
BOOL CStaticEx::OnEraseBkgnd(CDC* pDC)
{
CRect rc;
GetClientRect(&rc);
SYS_DEBUG_OUT(Output_Console,”rc.left=%d; rc.top=%d; rc.bottom=%d;rc.right=%d”,rc.left,rc.top,rc.bottom, rc.right);
pDC->BitBlt(0, 0, rc.Width(),rc.Height(), &m_memDC,0, 0 ,SRCCOPY);
return FALSE;
}
最新评论