DrawItem
?
DrawItem
??????????????????????????????????????
?
今天從CButton派生了一個(gè)類(lèi)CUIButton,主要用于自繪,按照基本的流程,重寫(xiě)DrawItem方法。
步驟如下:點(diǎn)擊CUIButton按鈕,在右鍵彈出菜單中選擇“add windows message Handler",
找到DrawItem,為其添加消息映射,添加的代碼如下:
void CUIButton::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
結(jié)果在使用到CUIButton的地方用SubClassDlgItem就會(huì)出問(wèn)題。
?
后來(lái)調(diào)試發(fā)現(xiàn),不應(yīng)該按照上面的添加此消息的映射,而是為CUIButton類(lèi)重寫(xiě)DrawItem函數(shù),添
加方法:
在類(lèi)CUIButton右鍵,在彈出菜單中選擇"Add Virtual Function",彈出的添加虛函數(shù)框中選
擇"DrawItem",向?qū)槲覀兩傻拇a如下:
void CUIButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
?
在這里添加所需的自繪代碼就ok了
?
?
?
附: how to implement control to self-draw
1、從CButton類(lèi)派生自己的CUIControl類(lèi)
2、借助于MFC向?qū)晒ぞ?#xff0c;為期添加虛函數(shù)DrawItem()和OnEraseBkgnd()。
???? 注意:DrawItem()是控件重定義的函數(shù),不是OnDrawItem()。
3、在DrawItem()中近控件的自繪處理,這里給出一個(gè)實(shí)例代碼,用于一個(gè)自定義Button,在
???? Button上面繪圖:
??? void CUIButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
?// TODO: Add your message handler code here and/or call default
?
?//CButton::OnDrawItem(nIDCtl, lpDrawItemStruct);
?int nCxIcon = ::GetSystemMetrics(SM_CXICON);
?int nCyIcon = ::GetSystemMetrics(SM_CYICON);
?CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
?CBitmap bitmap;
?bitmap.CreateCompatibleBitmap(pDC,nCxIcon,nCyIcon);
?CDC dcMem;
?dcMem.CreateCompatibleDC(pDC);
?CBitmap *pOldBitmap = (CBitmap *)dcMem.SelectObject(bitmap);
?ASSERT(pOldBitmap);
?HICON hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
?ASSERT(hIcon);
?CRect rcClient;
?GetClientRect(&rcClient); // get the button's rect
?dcMem.StretchBlt(0,0,nCxIcon,nCyIcon,pDC,2,2,rcClient.Width() - CX_SHADOW - 4,
??rcClient.Height() - CY_SHADOW - 4,SRCCOPY);
?
?dcMem.DrawIcon(0,0,hIcon);
?// draw border around icon
?CPen pen;
?pen.CreateStockObject(BLACK_PEN);
?ASSERT(pDC != NULL);
?CPen* pPenOld = pDC->SelectObject(&pen);
?pDC->Rectangle(0, 0, rcClient.Width()-CX_SHADOW, rcClient.Height()-CY_SHADOW);
?if (pPenOld)
??pDC->SelectObject(pPenOld);
?//pDC->StretchBlt(0,0,80,80,&dcMem,0,0,nCxIcon,nCyIcon,SRCCOPY);
?pDC->StretchBlt(2,2,rcClient.Width() - CX_SHADOW - 4,rcClient.Height() - CY_SHADOW - 4,&dcMem,0,0,nCxIcon,nCyIcon,SRCCOPY);
}
?
4、為OnEraseBkGround()添加代碼。這里很簡(jiǎn)單,直接返回True即可:
?? BOOL CUIButton::OnEraseBkgnd(CDC* pDC)
{
?// TODO: Add your message handler code here and/or call default
?return TRUE;
?//return CButton::OnEraseBkgnd(pDC);
}
5、在你的對(duì)話框中使用CUIButton按鈕,首先在dialog資源中添加一個(gè)按鈕(CButton)。
6、在對(duì)話框類(lèi)的頭文件中定義一個(gè)成員CUIButton m_CtlUIBtn;注意變量的類(lèi)型是CUIButton而
??? 不是CButton
7 、在OnInitDialog中用SubClass技術(shù):
???? BOOL CAboutDlg::OnInitDialog()
{
?CDialog::OnInitDialog();?
?m_CtlUIButton.SubclassDlgItem(IDC_UI_BUTTON,this);
??return TRUE;? // return TRUE unless you set the focus to a control
?????????????? // EXCEPTION: OCX Property Pages should return FALSE
}
?
that is OK!
?
【作者: ^_^ >> LP】【訪問(wèn)統(tǒng)計(jì): 】【2007年03月19日 星期一 10:51】【注冊(cè)】【打印】
總結(jié)