首页 > 代码库 > 简单的自绘CListBox,重载虚MeasureItem和DrawItem这两个虚函数
简单的自绘CListBox,重载虚MeasureItem和DrawItem这两个虚函数
[cpp] view plain copy
- //例如CNewListBox继承自CListBox,重载虚MeasureItem和DrawItem这两个虚函数,代码如下:
- void CNewListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
- {
- // TODO: Add your code to draw the specified item
- ASSERT(lpDrawItemStruct->CtlType == ODT_LISTBOX);
- LPCTSTR lpszText = (LPCTSTR) lpDrawItemStruct->itemData;
- ASSERT(lpszText != NULL);
- CDC dc;
- dc.Attach(lpDrawItemStruct->hDC);
- // Save these value to restore them when done drawing.
- COLORREF crOldTextColor = dc.GetTextColor();
- COLORREF crOldBkColor = dc.GetBkColor();
- // If this item is selected, set the background color
- // and the text color to appropriate values. Also, erase
- // rect by filling it with the background color.
- if ((lpDrawItemStruct->itemAction | ODA_SELECT) &&
- (lpDrawItemStruct->itemState & ODS_SELECTED))
- {
- dc.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
- dc.SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));
- dc.FillSolidRect(&lpDrawItemStruct->rcItem,
- ::GetSysColor(COLOR_HIGHLIGHT));
- }
- else
- {
- if(lpDrawItemStruct->itemID%2)
- dc.FillSolidRect(&lpDrawItemStruct->rcItem, RGB(128,128,128));
- else
- dc.FillSolidRect(&lpDrawItemStruct->rcItem, RGB(255,128,255));
- }
- // If this item has the focus, draw a red frame around the
- // item‘s rect.
- if ((lpDrawItemStruct->itemAction | ODA_FOCUS) &&
- (lpDrawItemStruct->itemState & ODS_FOCUS))
- {
- CBrush br(RGB(0, 0, 128));
- dc.FrameRect(&lpDrawItemStruct->rcItem, &br);
- }
- lpDrawItemStruct->rcItem.left += 5;
- // Draw the text.
- dc.DrawText(
- lpszText,
- strlen(lpszText),
- &lpDrawItemStruct->rcItem,
- DT_LEFT|DT_SINGLELINE|DT_VCENTER);
- // Reset the background color and the text color back to their
- // original values.
- dc.SetTextColor(crOldTextColor);
- dc.SetBkColor(crOldBkColor);
- dc.Detach();
- }
- void CNewListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
- {
- // TODO: Add your code to determine the size of specified item
- ASSERT(lpMeasureItemStruct->CtlType == ODT_LISTBOX);
- LPCTSTR lpszText = (LPCTSTR) lpMeasureItemStruct->itemData;
- ASSERT(lpszText != NULL);
- CSize sz;
- CDC* pDC = GetDC();
- sz = pDC->GetTextExtent(lpszText);
- ReleaseDC(pDC);
- lpMeasureItemStruct->itemHeight = 2*sz.cy;
- }
- // 其中m_listBox为CNewListBox类型的对象
- #define IDC_LISTBOX 0x1101
- m_listBox.Create(WS_CHILD|WS_VISIBLE|WS_BORDER|WS_VSCROLL|WS_HSCROLL|
- LBS_OWNERDRAWVARIABLE, CRect(0, 0, 380, 280), this, IDC_LISTBOX);
效果图如下所示:
http://blog.csdn.net/visualeleven/article/details/5935430
简单的自绘CListBox,重载虚MeasureItem和DrawItem这两个虚函数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。