1.控件源码:ColorListCtrl.h
//////////////////////////////////////////////////////////////////////////////// // 自己的ListBox // // author yuanyc // date 2012.01.12 // Copyright (c) 2012. 中软万维 // //////////////////////////////////////////////////////////////////////////////// #ifndef ColorListCtrl_H #define ColorListCtrl_H #include "../stdafx.h" #include <map> using namespace std; typedef CWinTraits<WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, 0> CColorListTraits; class CColorListCtrl : public CWindowImpl<CColorListCtrl, CListViewCtrl,CColorListTraits> , public CCustomDraw<CColorListCtrl> { private: typedef CWindowImpl<CColorListCtrl, CListViewCtrl, CColorListTraits> baseClass; public: DWORD OnPrePaint(int idCtrl, LPNMCUSTOMDRAW lpNMCD); DWORD OnItemPrePaint ( int idCtrl, NMCUSTOMDRAW* pnmcd ); void SetItemColor(int nItem, COLORREF nColor) { m_mapItemColor[nItem] = nColor; //RedrawItems(nItem, nItem); //UpdateWindow(); } void OnRButtonDown(UINT uMsg, CPoint ptx) { CMenu menu; menu.CreatePopupMenu(); menu.AppendMenu(MF_BYCOMMAND, MENU_CLEAR_LOG, _T("清除日志")); ::GetCursorPos(&ptx); int i = menu.TrackPopupMenu(TPM_RETURNCMD,ptx.x,ptx.y, m_hWnd); if (i == MENU_CLEAR_LOG) { DeleteAllItems(); m_mapItemColor.clear(); } SetMsgHandled(TRUE); } DECLARE_WND_SUPERCLASS(_T("WTL_CheckListView"), GetWndClassName()) BEGIN_MSG_MAP_EX(CColorListCtrl) MSG_WM_RBUTTONDOWN(OnRButtonDown) CHAIN_MSG_MAP_ALT(CCustomDraw<CColorListCtrl>, 1) DEFAULT_REFLECTION_HANDLER() END_MSG_MAP() public: map<int,COLORREF> m_mapItemColor; }; #endif /*ColorListCtrl_H*/
ColorListCtrl.cpp
#include "stdafx.h" #include "ColorListCtrl.h" #include <bkres/bkres.h> DWORD CColorListCtrl::OnPrePaint(int idCtrl, LPNMCUSTOMDRAW lpNMCD) { return CDRF_NOTIFYITEMDRAW; } DWORD CColorListCtrl::OnItemPrePaint ( int idCtrl, NMCUSTOMDRAW* pnmcd ) { NMLVCUSTOMDRAW* pnmlv = (NMLVCUSTOMDRAW*) pnmcd; map<int,COLORREF>::iterator pos; pos = m_mapItemColor.find(pnmlv->nmcd.dwItemSpec); if (pos != m_mapItemColor.end()) { pnmlv->clrText = pos->second; } else { AtlMessageBox(NULL,_T("ERROR")); } return CDRF_DODEFAULT; }
2.思想:1.用map来存储 键值对(行号和颜色)
2.重载OnPrePaint和OnPrePaint
3.用法。
在适当时机,如此调用,多线程,所以加了锁。
::EnterCriticalSection(&m_log_lock); int n = m_listLog.GetItemCount(); m_listLog.SetItemColor(n, RGB(0,255,0)); m_listLog.InsertItem(n,CA2T(strprogress.c_str())); ::LeaveCriticalSection(&m_log_lock);