简单的自绘CListBox,重载虚MeasureItem和DrawItem这两个虚函数
Posted 朝闻道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的自绘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这两个虚函数的主要内容,如果未能解决你的问题,请参考以下文章
自绘控件时添加LBS_OWNERDRAWFIXED风格,离奇报错的解决方案!