您的位置:首页 > 其它

对于有背景图片的对话框上的按钮如何透明

2013-04-06 17:52 369 查看
这里是重载CButton类,类名为CMyButton

1.重载虚函数PreSubclassWindow()

void CMyButton::PreSubclassWindow()
{
// TODO: Add your specialized code here and/or call the base class
ModifyStyle(0, BS_OWNERDRAW);//设置按钮类得自绘风格
CButton::PreSubclassWindow();
}


2.重载DrawItem()

void CMyButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// TODO: Add your code to draw the specified item

HDC hDestDC=lpDrawItemStruct->hDC;

CRect rc;
GetClientRect(rc);

int nWindth=rc.Width();
int nHeight=rc.Height();

HDC hParentDC;
hParentDC=::GetDC(::GetParent(m_hWnd));  //获取父窗口dc

HDC hDC=CreateCompatibleDC(lpDrawItemStruct->hDC);//创建兼容DC,
HBITMAP hBitmap=CreateCompatibleBitmap(lpDrawItemStruct->hDC,nWindth,nHeight);
HBITMAP hOldBitmap=(HBITMAP)SelectObject(hDC,hBitmap);

SetBkMode(hDC,TRANSPARENT);

//把父窗口的背景图复制到按钮的DC上,实现视觉透明----------------
CAlarmClock2Dlg *pParent=(CAlarmClock2Dlg *)GetParent();

CPoint pt(0,0);
MapWindowPoints(pParent,&pt,1);
::BitBlt(hDC,rc.left,rc.top,rc.Width(),rc.Height(),hParentDC,0,0,SRCCOPY);//不能少,不然按钮背景会为黑色

//====================================
CString strText;
GetWindowText(strText);

HFONT hFont=(HFONT)SendMessage(WM_GETFONT);
if(!hFont)
hFont=(HFONT)GetStockObject(DEFAULT_GUI_FONT);

HFONT hOldFont=(HFONT)SelectObject(hDC,hFont);

::SetTextColor(hDC,RGB(255,0,0));
::DrawText(hDC,strText,-1,&rc,DT_SINGLELINE|DT_CENTER|DT_VCENTER|DT_WORD_ELLIPSIS);
::SelectObject(hDC,hOldFont);

SelectClipRgn (hDC,NULL);
//复制到控件的DC上------------------------
BitBlt(hDestDC,0,0,nWindth,nHeight,hDC,0,0,SRCCOPY);

//释放资源
::SelectObject(hDC,hOldBitmap);
::DeleteObject(hBitmap);
::DeleteDC(hDC);
::DeleteDC(hParentDC);

}


3.将按钮关联一个CMyButton类对象

运行效果如下:



参考:自绘实现半透明水晶按钮 -- 源码分享
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: