第一首先向控件添加NM_CUSTOMDRAW消息。过程如下:
在头文件中添加:
afx_msg void OnCustomdrawMyList(NMHDR *pNMHDR, LRESULT *pResult); 为消息NM_CUSTOMDRAW的响应函数
在.CPP文件中添加
BEGIN_MESSAGE_MAP(CListControlDlg, CDialog)
//{{AFX_MSG_MAP(CListControlDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_NOTIFY ( NM_CUSTOMDRAW, IDC_LIST1, OnCustomdrawMyList ) //这句是你要添加的 其中IDC_LIST1控件的ID。
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
以下为重绘函数的实现过程:
void CListControlDlg::OnCustomdrawMyList(NMHDR *pNMHDR, LRESULT *pResult)
{
//设置整行的文字的颜色
/*
LPNMLVCUSTOMDRAW pLVCD = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR);
*pResult = CDRF_DODEFAULT;
// TODO: 在此添加控件通知处理程序代码
COLORREF crText;
if ( CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage )
{
*pResult = CDRF_NOTIFYITEMDRAW;
}
else if ( CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage )
{
*pResult = CDRF_NOTIFYSUBITEMDRAW;
}
else if (CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage)
{
if ( (pLVCD->nmcd.dwItemSpec % 3) == 0)
{
crText = RGB(255,0,0);
}
else if((pLVCD->nmcd.dwItemSpec % 3) == 1)
{
crText = RGB(0,255,0);
}
else
{
crText = RGB(128,128,255);
}
pLVCD->clrText = crText;
*pResult = CDRF_DODEFAULT;
}
*/
NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>(pNMHDR);
*pResult = 0;
if ( CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage )
{
*pResult = CDRF_NOTIFYITEMDRAW;
}
else if ( CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage )
{
*pResult = CDRF_NOTIFYSUBITEMDRAW;
}
else if ( (CDDS_ITEMPREPAINT | CDDS_SUBITEM) == pLVCD->nmcd.dwDrawStage )
{
COLORREF m_clrText;
int nItem = static_cast<int> (pLVCD->nmcd.dwItemSpec);
// 判断使ListCtrl不同颜色现实的条件
CString str = m_list.GetItemText(nItem ,2);//获取控件第二列的值,m_list为控件的变量
float m_height=(float)atof(str);
if (m_height>80&&2==pLVCD->iSubItem)
{
// 设置该列红色
m_clrText = RGB(255, 0, 0) ;
}
else
{
m_clrText = RGB(0, 0, 0) ;
}
pLVCD->clrText = m_clrText;
*pResult = CDRF_DODEFAULT;
}
}