简单的自绘CListBox(多行显示)

      之前写过一个自绘的CListBox类,详细请参考http://blog.csdn.net/VisualEleven/archive/2010/10/12/5935430.aspx
现在修改这之前的代码,使该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->DrawText(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")); }   

效果图如下所示:

你可能感兴趣的:(null,border,2010)