MFC CBitmapButton+文字写入

在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代码:

 1 #pragma once
2
3
4 // CImgButton
5
6 class CImgButton : public CBitmapButton
7 {
8 DECLARE_DYNAMIC(CImgButton)
9
10 public:
11 CImgButton();
12 virtual ~CImgButton();
13
14 protected:
15 DECLARE_MESSAGE_MAP()
16 public:
17
18 public:
19 COLORREF TextColor;
20 void SetTextColor(COLORREF crColor);
21
22 virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
23 };
24
25
26
27
28 // ImgButton.cpp : implementation file
29 //
30
31 #include "stdafx.h"
32 #include "win32Test.h"
33 #include "ImgButton.h"
34
35
36 // CImgButton
37
38 IMPLEMENT_DYNAMIC(CImgButton, CBitmapButton)
39
40 CImgButton::CImgButton()
41 {
42
43 }
44
45 CImgButton::~CImgButton()
46 {
47 }
48
49
50 BEGIN_MESSAGE_MAP(CImgButton, CBitmapButton)
51 END_MESSAGE_MAP()
52
53
54 void CImgButton::SetTextColor(COLORREF crColor)
55 {
56 TextColor = crColor;
57 }
58
59 void CImgButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
60 {
61
62 // TODO: Add your code to draw the specified item
63 CRect rect = lpDrawItemStruct->rcItem;
64 CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
65 int nSaveDC = pDC->SaveDC();
66 UINT state = lpDrawItemStruct->itemState;
67 TCHAR strText[MAX_PATH + 1];
68 ::GetWindowText(m_hWnd, strText, MAX_PATH);
69
70 CBitmapButton::DrawItem(lpDrawItemStruct);
71
72 pDC->SetTextColor(TextColor);
73 if (strText!=NULL)
74 {
75 CFont *hFont = GetFont();
76 CFont *hOldFont = pDC->SelectObject(hFont);
77 CSize szExtent = pDC->GetTextExtent(strText, lstrlen(strText));
78 CPoint pt(rect.CenterPoint().x - szExtent.cx / 2, rect.CenterPoint().y - szExtent.cy / 2);
79 if (state & ODS_SELECTED)
80 {
81 pt.Offset(1, 1);
82 }
83 int nMode = pDC->SetBkMode(TRANSPARENT);
84 if (state & ODS_DISABLED)
85 {
86 pDC->DrawState(pt, szExtent, strText, DSS_DISABLED, TRUE, 0, (HBRUSH)NULL);
87 }
88 else
89 {
90 pDC->DrawState(pt, szExtent, strText, DSS_NORMAL, TRUE, 0, (HBRUSH)NULL);
91 }
92 pDC->SelectObject(hOldFont);
93 pDC->SetBkMode(nMode);
94 }
95
96 pDC->RestoreDC(nSaveDC);
97 }

你可能感兴趣的:(bitmap)