CListCtrl 修改行和单元格的背景色或字体颜色

1. 添加 NM_CUSTOMDRAW 消息及其响应函数

 BEGIN_MESSAGE_MAP(DBMonitor, CDialog)

      ON_NOTIFY( NM_CUSTOMDRAW, IDC_LIST_RESULT/*CListCtrl的ID*/, OnCustomdrawListResult )

 ... ... END_MESSAGE_MAP()

 说明: 该类表控件 的 Owner Draw Fixed 属性值为 False

 2. 消息响应函数

void DBMonitor::OnCustomdrawListResult(NMHDR *pNMHDR, LRESULT *pResult)

      *pResult = CDRF_DODEFAULT;

       NMLVCUSTOMDRAW * lplvdr = reinterpret_cast(pNMHDR);

       NMCUSTOMDRAW &nmcd = lplvdr->nmcd;

       switch(lplvdr->nmcd.dwDrawStage)//判断状态

       {

            case CDDS_PREPAINT:

            {

                  *pResult = CDRF_NOTIFYITEMDRAW;

                  break;

            }

             case CDDS_ITEMPREPAINT:   //如果为画ITEM之前就要进行颜色的改变

             { // 设置指定行的背景颜色, m_mapItemColor为自定义的颜色集合

                  COLORREF ItemColor;

                  DWORD nIntex = nmcd.dwItemSpec;

                  if(m_mapItemColor.Lookup(nIntex, ItemColor))

                  {

                        lplvdr->clrTextBk = ItemColor; // 设置背景颜色

                  }

                   *pResult = CDRF_NOTIFYSUBITEMDRAW; //关键, 将消息细化给重绘 SubItem

             }

             break;

             case CDDS_ITEMPREPAINT | CDDS_SUBITEM: //重绘SubItem

             {

                  COLORREF clrIndicateText = RGB(255,0,0); //提示字段 字体为红色

                  COLORREF clrDefaultText = RGB(0,0,0); //其他字段 字体为黑色  

                 int nItem = static_cast( lplvdr->nmcd.dwItemSpec );

                 int nSubItem = static_cast(lplvdr->iSubItem);

                 pair point = make_pair(nItem, nSubItem);

                //set< pair > m_setDataDiff; 保存想重点提示的字段

                 if (m_setDataDiff.find(point) != m_setDataDiff.end())

                {

                      lplvdr->clrText = clrIndicateText;

                 }

                else

                 {

                      lplvdr->clrText = clrDefaultText;

                 }

                // Tell Windows to paint the control itself.

                *pResult = CDRF_DODEFAULT;

           }

           default:

                 break;

       }

 }

3. 触发重绘消息

 // 修改ClistCtrl类的指定行的颜色。

void DBMonitor::RedrawItemColor(int nFirst, int nLast)

{

     m_listResult.RedrawItems(nFirst, nLast);//重新染色

     UpdateWindow();

}

 4. 设置颜色集合 void DBMonitor::SaveColorSet()

{

     CMap<DWORD, DWORD&, COLORREF, COLORREF&> m_mapItemColor; //存储背景色的CMap

      COLORREF clr[5] = { RGB(255, 164, 255), RGB(177, 174, 244), RGB(170, 247, 249), RGB(245, 250, 169), RGB(249, 205, 170) };

      for (unsigned long i=0; i<10000; )

      {

           for (int j=0; j<2; ++j)

          {

              m_mapItemColor.SetAt( i, clr[j+2]);//设置某行的颜色

              ++i;

              m_mapItemColor.SetAt( i, clr[j+2]);

              ++i;

         }

     }

}

全部代码已上传至CSDN: <<数据库数据变化监控软件(自制)>> http://download.csdn.net/detail/wendan97/6729057

你可能感兴趣的:(mfc,VS2005,背景色,字体颜色,单元格,CListCtrl控件)