在class view的工程目录下,添加类CImgButton,继承自CBitmapButton。选择CImgButton类的property,重载DrawItem(不是Message下的WM_DRAWITEM,其响应函数OnDrawItem不会被调用到。为什么?),实现在bitmap上写入文字的功能。代码基本照搬http://topic.csdn.net/u/20070611/09/d59ec937-70b1-49f2-b8df-ff44a87b1a04.html里的,附于本文后。使用时,1)在dialog中拖入一个button,设置ownerdraw。2)装载需要的位图资源。3)对话框头文件中 #include "ImgButton.h" CImgButton m_cImgBtn; 4)对话框cpp中 m_cImgBtn.SubclassDlgItem(IDC_BUTTON5, this); m_cImgBtn.LoadBitmaps(IDB_BTNLONGU, IDB_BTNLONGD, IDB_BTNLONGU); m_cImgBtn.SizeToContent(); m_cImgBtn.SetTextColor(RGB(0,0,0)); 完成。
CImgButton代码:
#pragma once // CImgButton class CImgButton : public CBitmapButton { DECLARE_DYNAMIC(CImgButton) public: CImgButton(); virtual ~CImgButton(); protected: DECLARE_MESSAGE_MAP() public: public: COLORREF TextColor; void SetTextColor(COLORREF crColor); virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); }; // ImgButton.cpp : implementation file // #include "stdafx.h" #include "win32Test.h" #include "ImgButton.h" // CImgButton IMPLEMENT_DYNAMIC(CImgButton, CBitmapButton) CImgButton::CImgButton() { } CImgButton::~CImgButton() { } BEGIN_MESSAGE_MAP(CImgButton, CBitmapButton) END_MESSAGE_MAP() void CImgButton::SetTextColor(COLORREF crColor) { TextColor = crColor; } void CImgButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { // TODO: Add your code to draw the specified item CRect rect = lpDrawItemStruct->rcItem; CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC); int nSaveDC = pDC->SaveDC(); UINT state = lpDrawItemStruct->itemState; TCHAR strText[MAX_PATH + 1]; ::GetWindowText(m_hWnd, strText, MAX_PATH); CBitmapButton::DrawItem(lpDrawItemStruct); pDC->SetTextColor(TextColor); if (strText!=NULL) { CFont *hFont = GetFont(); CFont *hOldFont = pDC->SelectObject(hFont); CSize szExtent = pDC->GetTextExtent(strText, lstrlen(strText)); CPoint pt(rect.CenterPoint().x - szExtent.cx / 2, rect.CenterPoint().y - szExtent.cy / 2); if (state & ODS_SELECTED) { pt.Offset(1, 1); } int nMode = pDC->SetBkMode(TRANSPARENT); if (state & ODS_DISABLED) { pDC->DrawState(pt, szExtent, strText, DSS_DISABLED, TRUE, 0, (HBRUSH)NULL); } else { pDC->DrawState(pt, szExtent, strText, DSS_NORMAL, TRUE, 0, (HBRUSH)NULL); } pDC->SelectObject(hOldFont); pDC->SetBkMode(nMode); } pDC->RestoreDC(nSaveDC); }