1.新建一个对话框工程,为对话框类定义如下几个变量:
CBitmap m_pBitmapTime;//保存控件背景图
CRect m_rectTime;//保存控件的大小和位置.
BOOL m_bFirstTime;判断是否第一次调用OnPaint(),要在此函数中获得控件背景图及大小
2.在对话框类构造函数中初始化m_bFirstTime:
m_bFirstTime=TRUE;
3.为对话框类增加自定义的成员函数LoadBackBitmap:
void CYourDlg::LoadBackBitmap(UINT uID,CBitmap* pBitmap, RECT &rect)//获得控件背景图及大小.
{ // if(m_pBitmap!=NULL) return;
CRect rect1;
POINT pnt;
int iWidth=0,iHigh=0;
CWnd* pWnd=GetDlgItem(uID);
GetClientRect(&rect1); pWnd->GetWindowRect(&rect);
ScreenToClient(&rect);
pnt.x=rect.left;pnt.y=rect.top;
CPaintDC dc(this);
CDC memDC;
memDC.CreateCompatibleDC(&dc);
pBitmap->CreateCompatibleBitmap( &dc,rect.right-rect.left-iWidth,rect.bottom-rect.top-iHigh);
memDC.SelectObject(pBitmap);
memDC.StretchBlt(0, 0, rect.right-rect.left-iWidth,rect.bottom-rect.top-iHigh, &dc, rect.left+iHigh/2, rect.top+iHigh/2,rect.right-rect.left-iWidth,rect.bottom-rect.top-iHigh, SRCCOPY);
memDC.DeleteDC();
}
在void CYourDlg::OnPaint()中加入如下代码:
if(m_bFirstTime){
m_bFirstTime=FALSE;
LoadBackBitmap(IDC_STATIC_TIMECD,&m_pBitmapTime,m_rectTime);
} 4.然后在对话框类的OnCtlColor函数的最前面加入:
if(pWnd->GetDlgCtrlID()==IDC_STATIC_TIMECD)
{ //pDC->SetTextColor(RGB(255,0,0));
pDC->SetBkMode(TRANSPARENT);
CDC memDC;
memDC.CreateCompatibleDC(pDC);
memDC.SelectObject(&m_pBitmapTime);
pDC->BitBlt(0, 0, m_rectTime.Width(), m_rectTime.Height(), &memDC, 0, 0, SRCCOPY);
memDC.DeleteDC();
return (HBRUSH)GetStockObject(NULL_BRUSH);
}
这样就实现了控件的透明,而且无需考虑最头疼的控件文本改变后的重绘问题.