I have seen a lot of requests asking how to implement a list control with different colors in each row. After a long time, taking a lot of useful information from this site, it's time to give back something. So, this MFC wrapper code just replaces the
CListCtrl control with one that alternates the row color of the control.
Using the code
This class uses the
OnEraseBkgnd to accomplish the alternate color effect. The big job is done in the
OnEraseBkgnd function, since this part of the code is responsible to "paint" our object. We have to find how many rows are shown as well as the height of each row. We receive these information from the
::GetItemPosition (you can refer to MSDN for details) respectively. From this point and after, things are easy.
BOOL CColoredListCtrl::OnEraseBkgnd(CDC* pDC)
// TODO: Add your message handler code here
// and/or call default
for (int i=0;i<=chunk_height;i++)
pDC->FillRect(&rect,i %2 ? &brush1 : &brush0);
To use this code, add the
CColoredListCtrl class to your project and replace any
CListCtrl with this one.
If you want to change the default color of the rows, just replace the
m_colRow2 variables in the
CColoredListCtrl constructor with the colors you prefer.
The default text color is black RGB(0,0,0). If you also want to change the item's text color then replace the code
lplvcd->clrText = RGB(0,0,0); that you can find in the
CColoredListCtrl::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult) function.