1.首先从CListCtrl 继承一个类,命名为CXListCtrl
在头文件中加摸板
CMap<DWORD, DWORD&, COLORREF, COLORREF&> MapItemColor;
CMap<DWORD, DWORD&, COLORREF, COLORREF&> MapFontColor;
好在这里查找你的修改的颜色。
2.自己写个消息映射,可能添加不上,要自己写。
头文件
DECLARE_MESSAGE_MAP()
实现文件
BEGIN_MESSAGE_MAP(CXListCtrl, CListCtrl)
ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdraw)
END_MESSAGE_MAP()
OnNMCustomdraw 为实现函数。
3.重写OnNMCustomdraw函数。
void CXListCtrl::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult)
{
NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>(pNMHDR); //首先声明一个NMLVCUSTOMDRAW结构体的指针pLVCD,关联pNMHDR,为了下面的操作。
// Take the default processing unless we set this to something else below.
*pResult = CDRF_DODEFAULT;
// First thing - check the draw stage. If it's the control's prepaint
// stage, then tell Windows we want messages for every item.
if (CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage)
{
*pResult = CDRF_NOTIFYITEMDRAW;
}
else if (CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage)
{
// This is the notification message for an item. We'll request
// notifications before each subitem's prepaint stage.
*pResult = CDRF_NOTIFYSUBITEMDRAW;
}
else if ((CDDS_ITEMPREPAINT | CDDS_SUBITEM) == pLVCD->nmcd.dwDrawStage) //仅当pLVCD结构体中nmcd成员的dwDrawStage状态为CDDS_ITEMPREPAINT | CDDS_SUBITEM时
{ //我们就可以判断“行”和“列”,从而来设置文字颜色和文字背景颜色了。
// This is the prepaint stage for a subitem. Here's where we set the
// item's text and background colors. Our return value will tell
// Windows to draw the subitem itself, but it will use the new colors
// we set here.
COLORREF ItemColor;
DWORD dw = (pLVCD->iSubItem + m_Col * pLVCD->nmcd.dwItemSpec);
// 根据在 SetCellColor(DWORD iItem, COLORREF color) 设置的 ITEM号和COLORREF 在摸板中查找,然后进行颜色赋值。
if (MapItemColor.Lookup(dw, ItemColor))
{
pLVCD->clrTextBk = ItemColor;
// SetFont(m_Font, false);
}
else
{
pLVCD->clrTextBk = 16777215;//如果不是选择的“行”和“列”就设置成系统默认的那种颜色
}
if (MapFontColor.Lookup(dw, ItemColor))
{
pLVCD->clrText = ItemColor;
// SetFont(m_Font, false);
}
else
{
pLVCD->clrText = 0;
}
/*
if (pLVCD->iSubItem == m_iRow)
{
if (m_FontFlag)
{
m_FontFlag = FALSE;
SetFont(m_Font, false);
}
}
*/
*pResult = CDRF_DODEFAULT;
}
}
4.修改指定单元格的颜色。
void CXListCtrl::SetCellColor(int iRow, int iCol, COLORREF color)
{
CHeaderCtrl* pHeaderCtrl = GetHeaderCtrl();
if (pHeaderCtrl)
{
m_Col = pHeaderCtrl->GetItemCount();
}
DWORD iItem = iRow * m_Col + iCol;
MapItemColor.SetAt(iItem, color);//设置某行的颜色。
this->RedrawItems(iRow, iRow);//重新染色
this->SetFocus(); //设置焦点
UpdateWindow();
}
void CXListCtrl::SetFontColor(int iRow, int iCol, COLORREF color)
{
CHeaderCtrl* pHeaderCtrl = GetHeaderCtrl();
if (pHeaderCtrl)
{
m_Col = pHeaderCtrl->GetItemCount();
}
DWORD iItem = iRow * m_Col + iCol;
MapFontColor.SetAt(iItem, color);//设置单元格字体的颜色
this->RedrawItems(iRow, iRow);//重新染色
this->SetFocus(); //设置焦点
UpdateWindow();
}