为ListCtrl列表控件设置颜色

来源:互联网 发布:淘宝质量问题怎么投诉 编辑:程序博客网 时间:2024/05/22 17:31

为ListCtrl控件设置颜色,主要是在NM_CUSTOMDRAW的消息的响应函数中进行。新建一个对话框应用程序,拖一个列表控件,并未列表控件添加些测试数据。

为列表控件绑定一个CListCtrl的派生类CMyList。

主要代码如下:

#pragma once// CMyListclass CMyList : public CListCtrl{DECLARE_DYNAMIC(CMyList)public:CMyList();virtual ~CMyList();protected:DECLARE_MESSAGE_MAP()public:int m_nPreIndex;int m_nCurIndex;afx_msg void OnMouseMove(UINT nFlags, CPoint point);afx_msg void OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult);};

// MyList.cpp : 实现文件//#include "stdafx.h"#include "ListColor.h"#include "MyList.h"// CMyListIMPLEMENT_DYNAMIC(CMyList, CListCtrl)CMyList::CMyList(){m_nPreIndex = -1;m_nCurIndex = -1;}CMyList::~CMyList(){}BEGIN_MESSAGE_MAP(CMyList, CListCtrl)ON_WM_MOUSEMOVE()ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, &CMyList::OnNMCustomdraw)END_MESSAGE_MAP()// CMyList 消息处理程序void CMyList::OnMouseMove(UINT nFlags, CPoint point){CRect rt;int nCurIndex = HitTest(point);if (nCurIndex != m_nCurIndex){m_nPreIndex = m_nCurIndex;m_nCurIndex = nCurIndex;GetItemRect(m_nPreIndex,&rt,LVIR_BOUNDS);InvalidateRect(&rt,TRUE);GetItemRect(m_nCurIndex,&rt,LVIR_BOUNDS);InvalidateRect(&rt,TRUE);}CListCtrl::OnMouseMove(nFlags, point);}void CMyList::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult){/*LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);*/LPNMLVCUSTOMDRAW p = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR);*pResult = 0;int nCurItemIndex = p->nmcd.dwItemSpec;if (p->nmcd.dwDrawStage == CDDS_PREPAINT){*pResult = CDRF_NOTIFYITEMDRAW;}else{if(nCurItemIndex == m_nCurIndex){ p->clrTextBk = RGB(255,0,0);p->clrText= RGB(255,255,255);}else if(p->nmcd.uItemState == CDIS_SELECTED){ //选中行p->clrTextBk = RGB(255,255,255);p->clrText = RGB(0,0,0);::SetTextColor(p->nmcd.hdc,RGB(0,0,0));}else if(nCurItemIndex % 2 == 0){//偶数行p->clrTextBk = RGB(50,50,0);p->clrText = RGB(255,255,255);}else{//奇数行 p->clrTextBk = RGB(50,200,50);p->clrText = RGB(255,255,255);}*pResult = CDRF_NEWFONT;}}



原创粉丝点击