VC 中改變ListCtrl每一行的文字顏色

通過處理NM_CUSTOMDRAW,可以實現你的功能!但是NM_CUSTOMDRAW在Class Wizard中有可能看不到,不用管他,直接按照小面的方法添加處理過程即可!
1. 在消息映射表中
BEGIN_MESSAGE_MAP(CIHISSERVERView, CListView)
//{{AFX_MSG_MAP(CIHISSERVERView)
...
ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
...
//}}AFX_MSG_MAP
// Standard printing commands
END_MESSAGE_MAP()
2.在頭文件中
afx_msg void OnCustomDraw(NMHDR*, LRESULT*);
3.在cpp文件中
void CIHISSERVERView::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
{
// Contains information specific to an NM_CUSTOMDRAW
// notification message sent by a list-view control.
// mean:draw each item.set txt color,bkcolor....
NMLVCUSTOMDRAW* pLVCD = (NMLVCUSTOMDRAW*)(pNMHDR);
// Take the default processing unless we set this to something else below.
*pResult = CDRF_NEWFONT;
// First thing - check the draw stage. If it's the control's prepaint
// stage, then tell Windows we want messages for every item.
if ( pLVCD->nmcd.dwDrawStage==CDDS_PREPAINT)
{
*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_crTextBk , m_clrText;
int nItem = static_cast<int> (pLVCD->nmcd.dwItemSpec);
// 判斷使ListCtrl不同顏色現實的條件 CListCtrl &m_list = GetListCtrl();
CString str1 = m_list.GetItemText(nItem ,15);
bool bDBImplFail = false ;
if (str1 == "信息不祥")
{
m_crTextBk = RGB(255, 255, 0) ;
m_clrText = RGB(128, 0, 128) ;
} else
{ m_crTextBk = RGB(150, 255, 255);
m_clrText = RGB(12,26,234);
}
pLVCD->clrTextBk = m_crTextBk;
pLVCD->clrText = m_clrText;
*pResult = CDRF_DODEFAULT;
}
}


然後要在listctrl中增加記錄的時候,示例代碼如下:
// TODO: 在此添加額外的初始化代碼
m_msgListCtrl.InsertColumn(0,"時間");
m_msgListCtrl.InsertColumn(1,"內容",LVCFMT_LEFT);
m_msgListCtrl.SetColumnWidth(0,50);
m_msgListCtrl.SetColumnWidth(1,500);

for(int i=0;i<50;i++){
int index=m_msgListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE,"內容1");
m_msgListCtrl.SetItemText(index,1,"什麼?");
}

記住:用InsertItem插入一行的時候,其item的值並不是從0一直遞增的,必須像上面一樣寫。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章