简单的自绘CListBox(多行显示)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
简单的自绘CListBox(多行显示)
简单的自绘CListBox(多行显示)
// 重写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_WORDBREAK);
// Reset the background color and the text color back to their // original values.
dc.SetTextColor(crOldTextColor);
dc.SetBkColor(crOldBkColor);
dc.Detach();
}
// 重写MeasureItem虚函数
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);
CRect rect;
GetItemRect(lpMeasureItemStruct->itemID, &rect);
CDC* pDC = GetDC();
lpMeasureItemStruct->itemHeight = pDC->DrawT ext(lpszText, -1, rect, DT_WORDBREAK | DT_CALCRECT);
ReleaseDC(pDC);
}
// 调用方法
CNewListBox m_listBox; // 成员变量
#define IDC_LISTBOX 0x1010
m_listBox.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_HSCROLL | WS_VSCROLL |
LBS_OWNERDRAWVARIABLE , CRect(0, 0, 300, 200), this, IDC_LISTBOX);
for(int i=0; i<10; i++)
{
if(i%2)
m_listBox.AddString(_T("Hello,World1/r/nHello,World2"));
else
m_listBox.AddString(_T("Hello,World"));
}
效果图如下所示:。