大家经常用到listctrl 做表格 为了好看,要给每行设置不同背景色。很实用的一个小技巧。
1:首先在.h里添加以下消息
afx_msg void OnDrawColorForMyList(NMHDR *pNmHdr, LRESULT *pResult )
2:然后在.cpp里添加入口消息
ON_NOTIFY( NM_CUSTOMDRAW, IDC_LIST1, OnDrawColorForList ) //为改变颜色添加的消息
3:最后添加函数
void CTDlg::OnDrawColorForList ( NMHDR *pNmHdr, LRESULT *pResult )
{
NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNmHdr );
*pResult = CDRF_DODEFAULT;
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 clrNewTextColor, clrNewBkColor;
int nItem = static_cast<int>( pLVCD->nmcd.dwItemSpec );//获得子项
if( nItem%2 ==0 )//设置背景色
{
clrNewBkColor = RGB( 240, 240, 240 ); //偶数行背景色为灰色
clrNewTextColor = RGB( 255, 0, 0 );
}
else
{
clrNewBkColor = RGB( 255, 255, 255 ); //奇数行背景色为白色
clrNewTextColor = RGB( 0, 0, 0 );
}
pLVCD->clrText = clrNewTextColor;
pLVCD->clrTextBk = clrNewBkColor;
*pResult = CDRF_DODEFAULT;
}
}