最近在写一款山寨的反病毒软件,大致功能已经实现,还有一些细小的环节需要细化。

其中,在界面编程中,就用到了给ListCtrl控件着色,查看了网上一些文章,终于实现了。

其实说白了,原理很简单,就是ListCtrl在插入一个Item的时候,会发送一个NM_CUSTOMDRAW的消息,我们只要实现这个消息响应函数,并在里面绘制我们的颜色就可以了。

但是响应这个消息在VC6.0下需要自己实现:

1.在头文件中声明函数:afx_msg void OnCustomdrawMyList( NMHDR* pNMHDR, LRESULT* pResult ); 

2.在cpp文件中添加消息映射:ON_NOTIFY(NM_CUSTOMDRAW, IDC_LIST, OnCustomdrawMyList)

3.函数的实现:

void CXXX::OnCustomdrawMyList( NMHDR* pNMHDR, LRESULT* pResult )

{

 NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );

 

    // Take the default processing unless we set this to something else below.

    *pResult = 0;

 

    // 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;

 }

 

 // This is the notification message for an item. We'll request

 // notifications before each subitem's prepaint stage.

 else if ( pLVCD->nmcd.dwDrawStage==CDDS_ITEMPREPAINT )

 {

  COLORREF m_clrText;

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

  

  // 根据文本内容判断使ListCtrl不同颜色现实的条件

  CString str = m_list.GetItemText(nItem ,0);

  if (str == "0")

  {

   m_clrText = RGB(12,26,234);

  }

  else if (str == "1")

  {

   m_clrText = RGB(0,0,0);

  }

  else

  {

   m_clrText = RGB(255, 0, 0);

  }

  pLVCD->clrText = m_clrText;

  *pResult = CDRF_DODEFAULT;

 }

}