1. //自繪CListCtrl類,重載虛函數DrawItem
2.
3. void CNewListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
4. {
5. // TODO: Add your code to draw the specified item
6. ASSERT(lpDrawItemStruct->CtlType == ODT_LISTVIEW);
7. CDC dc;
8. dc.Attach(lpDrawItemStruct->hDC);
9. ASSERT(NULL != dc.GetSafeHdc());
10. // Save these value to restore them when done drawing.
11. COLORREF crOldTextColor = dc.GetTextColor();
12. COLORREF crOldBkColor = dc.GetBkColor();
13.
14. // If this item is selected, set the background color
15. // and the text color to appropriate values. Also, erase
16. // rect by filling it with the background color.
17. if ((lpDrawItemStruct->itemAction | ODA_SELECT) &&
18. (lpDrawItemStruct->itemState & ODS_SELECTED))
19. {
20. dc.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
21. dc.SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));
22. dc.FillSolidRect(&lpDrawItemStruct->rcItem,
23. ::GetSysColor(COLOR_HIGHLIGHT));
24. }
25. else
26. {
27. if(lpDrawItemStruct->itemID%2)
28. dc.FillSolidRect(&lpDrawItemStruct->rcItem, RGB(128,128,128));
29. else
30. dc.FillSolidRect(&lpDrawItemStruct->rcItem, RGB(255,128,255));
31. }
32.
33. // If this item has the focus, draw a red frame around the
34. // item's rect.
35. if ((lpDrawItemStruct->itemAction | ODA_FOCUS) &&
36. (lpDrawItemStruct->itemState & ODS_FOCUS))
37. {
38. CBrush br(RGB(0, 0, 128));
39. dc.FrameRect(&lpDrawItemStruct->rcItem, &br);
40. }
41.
42. // Draw the text.
43. CString strText(_T(""));
44. CRect rcItem;
45.
46. for(int i=0; i<GetHeaderCtrl()->GetItemCount(); i++)
47. {
48. strText = GetItemText(lpDrawItemStruct->itemID, i);
49. GetSubItemRect(lpDrawItemStruct->itemID, i, LVIR_LABEL, rcItem);
50. rcItem.left += 5;
51. dc.DrawText(
52. strText,
53. strText.GetLength(),
54. &rcItem,
55. DT_LEFT|DT_SINGLELINE|DT_VCENTER);
56. }
57.
58. // Reset the background color and the text color back to their
59. // original values.
60. dc.SetTextColor(crOldTextColor);
61. dc.SetBkColor(crOldBkColor);
62.
63. dc.Detach();
64.}
65.
66.// 調用
67.
68.CNewListCtrl m_list; // 類的成員變量
69.
70.
71.
72.#define IDC_LIST 0x1101
73. m_list.Create(WS_CHILD|WS_VISIBLE|WS_BORDER|WS_VSCROLL|WS_HSCROLL|LVS_OWNERDRAWFIXED, CRect(0, 0, 280, 280), this, IDC_LIST);
74. m_list.ModifyStyle(0, LVS_REPORT|LVS_SINGLESEL);
75. m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
76. m_list.InsertColumn(0, _T("AAA"), LVCFMT_LEFT, 100);
77. m_list.InsertColumn(1, _T("BBB"), LVCFMT_LEFT, 100);
78.
79. CString strText(_T(""));
80. for(int i=0; i<20; i++)
81. {
82. m_list.InsertItem(i, _T(""));
83. strText.Format(_T("%d - Hello, World!"), i+1);
84. m_list.SetItemText(i, 0, strText);
85. strText.Format(_T("%d - ABCDEFG"), i+1);
86. m_list.SetItemText(i, 1, strText);
87. }
顯示效果如下圖所示: