首页 > 代码库 > VC自绘ListCtrl(III) -- Alternate Row Colors for the CListCtrl

VC自绘ListCtrl(III) -- Alternate Row Colors for the CListCtrl

问题是这样的: 一般情况下,如果ListCtrl 的某个 Item 被选中的时候,它的背景会显示为蓝色,这时候如果我们点击一下其它的Button (也就是输入焦点转移到其它控件上去时),刚才这个被选中的item的背景会变成浅灰色,在这种情况下我要让它的背景仍然是蓝色,应该怎么实现?谢谢!


http://www.codeproject.com/listctrl/coloredlistctrl.asp


Alternate Row Colors for the CListCtrl

  • Download demo project - 18.8 Kb
  • Download source - 1.75 Kb

Sample Image

Introduction

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 theCListCtrl control with one that alternates the row color of the control.

Using the code

This class uses the OnCustomDraw and OnEraseBkgnd to accomplish the alternate color effect. The big job is done in theOnEraseBkgnd 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::GetCountPerPage and ::GetItemPosition (you can refer to MSDN for details) respectively. From this point and after, things are easy.

Collapse |Copy Code
BOOL CColoredListCtrl::OnEraseBkgnd(CDC* pDC) 
{
  // TODO: Add your message handler code here
  //       and/or call default

  CRect rect;
  CColoredListCtrl::GetClientRect(rect);


  POINT mypoint;  
  
  CBrush brush0(m_colRow1);
  CBrush brush1(m_colRow2);


 
  int chunk_height=GetCountPerPage();
  pDC->FillRect(&rect,&brush1);

  for (int i=0;i<=chunk_height;i++)
  {
    GetItemPosition(i,&mypoint);
    rect.top=mypoint.y ;
    GetItemPosition(i+1,&mypoint);
    rect.bottom =mypoint.y;
    pDC->FillRect(&rect,i %2 ? &brush1 : &brush0);
  }

  brush0.DeleteObject();
  brush1.DeleteObject();

  return FALSE;
}

To use this code, add the CColoredListCtrl class to your project and replace anyCListCtrl with this one.

If you want to change the default color of the rows, just replace the m_colRow1 andm_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 codelplvcd->clrText = RGB(0,0,0); that you can find in theCColoredListCtrl::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult) function.



VC自绘ListCtrl(III) -- Alternate Row Colors for the CListCtrl