首先建立以CMFCListCtrl为基类的CMyListCtrl,并重载OnGetCellTextColor以便设置文本颜色,重载OnGetCellBkColor以便设置背景颜色,重载OnGetCellFont以便设置字体,重载OnCompareItems以便按照一定规则排序。重载的关键函数如下:
COLORREF CMyListCtrl::OnGetCellTextColor(int nRow,int nColum)
{
if (!m_bColor)
{
return CMFCListCtrl::OnGetCellTextColor(nRow,nColum);
}
if (m_bRowTextColorIsRed[nRow] == TRUE)
{
returnRGB(100, 0, 0);
}
if (nRow % 2 == 0)
{
returnRGB(40, 40, 40);
}
if (nRow % 2 !=0)
{
returnRGB(50, 50, 50);
}
}
COLORREF CMyListCtrl::OnGetCellBkColor(int nRow,int nColum)
{
if (!m_bColor)
{
returnCMFCListCtrl::OnGetCellBkColor(nRow, nColum);
}
COLORREFcolorRef;
switch (m_nMyColorStyle)
{
case 0:
colorRef= (nRow % 2) == 0 ? RGB(167, 191, 222) : RGB(211, 223, 238);
break;
case 1:
colorRef= (nRow % 2) == 0 ? RGB(191, 177, 208) : RGB(223, 216, 232) ;
break;
case 2:
colorRef= (nRow % 2) == 0 ? RGB(205, 221, 172) : RGB(230, 238, 213) ;
break;
}
return colorRef;
}
HFONT CMyListCtrl::OnGetCellFont(int nRow,int nColum,DWORD dwData )
{
if (!m_bModifyFont)
{
return NULL;
}
if (nRow == nCurrentSel)//
{
returnafxGlobalData.fontDefaultGUIBold;
}
return NULL;
}
intCMyListCtrl::OnCompareItems(LPARAM lParam1, LPARAM lParam2,int iColumn)
{
CStringstrItem1 = GetItemText((int)(lParam1 <lParam2 ? lParam1 : lParam2), iColumn);
CStringstrItem2 = GetItemText((int)(lParam1 <lParam2 ? lParam2 : lParam1), iColumn);
if (iColumn == 0)
{
int nItem1 =_ttoi(strItem1);
int nItem2 =_ttoi(strItem2);
return(nItem1< nItem2 ? -1 : 1);
}
else
{
int iSort =_tcsicmp(strItem1, strItem2);
return(iSort);
}
}
对于CMyListCtrl的引用,添加数据后,可以得到相应颜色和底色的列表框,可以在列表框的双击消息中加入引用代码,使得双击后的行字体变黑。
POSITION pos = m_List.GetFirstSelectedItemPosition();
if(pos == NULL)
{
TRACE(_T("No items were selected!\n"));
}
else
{
while (pos)
{
int nItem = m_List.GetNextSelectedItem(pos);
TRACE(_T("Item %dwas selected!\n"), nItem);
m_List.nCurrentSel= nItem;
}
}
m_List.RedrawWindow();