三个接口函数,设置某一行的文字颜色(前景色)和背景色,使用说明都放在注释里了,创建的列表要使用该类声明,如:CColorListCtrl m_List;
那么使用时,直接通过m_List.SetItemColor(1,RGB(0,0,0),RGB(255,255,255));设置颜色即可
ColorListCtrl.h
#pragma once #include "afxcmn.h" typedef struct { COLORREF colText; COLORREF colTextBk; }TEXT_BK; class CColorListCtrl :public CListCtrl { public: CColorListCtrl(); ~CColorListCtrl(); public: void SetItemColor(DWORD iItem, COLORREF TextColor, COLORREF TextBkColor); //设置某一行的前景色和背景色 void SetAllItemColor(DWORD iItem, COLORREF TextColor, COLORREF TextBkColor);//设置全部行的前景色和背景色 void ClearColor(); //清除颜色映射表 CMap<DWORD, DWORD&, TEXT_BK, TEXT_BK&> MapItemColor; protected: //{{AFX_MSG(CColorListCtrl) //}}AFX_MSG void CColorListCtrl::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult); DECLARE_MESSAGE_MAP() };
ColorListCtrl.cpp:
#include "StdAfx.h" #include "ColorListCtrl.h" CColorListCtrl::CColorListCtrl() { } CColorListCtrl::~CColorListCtrl() { } BEGIN_MESSAGE_MAP(CColorListCtrl, CListCtrl) //{{AFX_MSG_MAP(CLineColorListCtrl) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdraw) END_MESSAGE_MAP() void CColorListCtrl::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: Add your control notification handler code here *pResult = CDRF_DODEFAULT; NMLVCUSTOMDRAW * lplvdr=(NMLVCUSTOMDRAW*)pNMHDR; NMCUSTOMDRAW &nmcd = lplvdr->nmcd; switch(lplvdr->nmcd.dwDrawStage)//判断状态 { case CDDS_PREPAINT: { *pResult = CDRF_NOTIFYITEMDRAW; break; } case CDDS_ITEMPREPAINT://如果为画ITEM之前就要进行颜色的改变 { TEXT_BK tb; if(MapItemColor.Lookup(nmcd.dwItemSpec, tb)) // 根据在 SetItemColor(DWORD iItem, COLORREF color) 设置的 // ITEM号和COLORREF 在摸板中查找,然后进行颜色赋值。 { lplvdr->clrText = tb.colText; lplvdr->clrTextBk = tb.colTextBk; *pResult = CDRF_DODEFAULT; } } break; } } void CColorListCtrl::ClearColor() { MapItemColor.RemoveAll(); } void CColorListCtrl::SetItemColor(DWORD iItem, COLORREF TextColor, COLORREF TextBkColor) { TEXT_BK tb; tb.colText = TextColor; tb.colTextBk = TextBkColor; MapItemColor.SetAt(iItem, tb);//设置某行的颜色。 this->RedrawItems(iItem, iItem);//重新染色 //this->SetCheck(iItem,1); this->SetFocus(); //设置焦点 UpdateWindow(); } void CColorListCtrl::SetAllItemColor(DWORD iItem, COLORREF TextColor, COLORREF TextBkColor) { //INT_PTR ncount = this->GetItemCount(); TEXT_BK tb; tb.colText = TextColor; tb.colTextBk = TextBkColor; if(iItem > 0) { for(DWORD numItem = 0; numItem < iItem ;numItem ++) { //iItem = i; MapItemColor.SetAt(numItem, tb); this->RedrawItems(numItem, numItem); } } return; }