ListCtrl控件著色
最近在寫一款山寨的反病毒軟件,大致功能已經實現,還有一些細小的環節需要細化。
其中,在界面編程中,就用到了給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;
}
}
