1. 程式人生 > >VC之列表控制元件背景色設定

VC之列表控制元件背景色設定

CMyListCtrl2::CMyListCtrl2()
{
	m_colRow1 = RGB(240,247,249);
	m_colRow2 = RGB(229,232,239);
}

CMyListCtrl2::~CMyListCtrl2()
{
}


BEGIN_MESSAGE_MAP(CMyListCtrl2, CListCtrl)
	//{{AFX_MSG_MAP(CMyListCtrl2)
	ON_WM_ERASEBKGND()
	ON_WM_PAINT()
	ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMyListCtrl2 message handlers

BOOL CMyListCtrl2::OnEraseBkgnd(CDC* pDC) 
{
	// TODO: Add your message handler code here and/or call default
	return TRUE;
//	return CListCtrl::OnEraseBkgnd(pDC);
}
//OnEraseBkgnd和OnPaint一起設定整個大的背景
void CMyListCtrl2::OnPaint() 
{
	CPaintDC dc(this); // device context for painting
	
	// TODO: Add your message handler code here
	CRect rcClient;
	GetClientRect(&rcClient);

	CDC dcMem;
	CBitmap bmpMem;

	//use temporary bitmap to avoid flickering
	dcMem.CreateCompatibleDC(&dc);
	if (bmpMem.CreateCompatibleBitmap(&dc,rcClient.Width(),rcClient.Height()))
	{
		CBitmap* pOldBmp = dcMem.SelectObject(&bmpMem);

		POINT mypoint;
		CBrush brush0(m_colRow1);
		CBrush brush1(m_colRow2);

		int chunk_height = GetItemCount();
		if (chunk_height < GetCountPerPage())
		{
			chunk_height = GetCountPerPage();
		}
		dcMem.FillRect(&rcClient,&brush1);

		for (int i=0; i<= chunk_height; i++)
		{
			GetItemPosition(i,&mypoint);
			rcClient.top = mypoint.y;
			GetItemPosition(i+1,&mypoint);
			rcClient.bottom = mypoint.y;
			dcMem.FillRect(&rcClient,i%2?&brush1:&brush0);
		}
		brush0.DeleteObject();
		brush1.DeleteObject();

		//paint the window onto the memory bitmap
		CWnd::DefWindowProc(WM_PAINT,(WPARAM)dcMem.m_hDC,0);

		//copy it to the window's DC
		dc.BitBlt(0,0,rcClient.right,rcClient.bottom,&dcMem,0,0,SRCCOPY);

		dcMem.SelectObject(pOldBmp);

		GetHeaderCtrl()->Invalidate(FALSE);

		bmpMem.DeleteObject();
	}
	dcMem.DeleteDC();
	
	// Do not call CListCtrl::OnPaint() for painting messages
}

void CMyListCtrl2::OnCustomDraw(NMHDR *pNMHDR, LRESULT *pResult)
{
	*pResult = 0;  
	LPNMLVCUSTOMDRAW  lplvcd = (LPNMLVCUSTOMDRAW)pNMHDR;
	int iRow = lplvcd->nmcd.dwItemSpec;
	switch(lplvcd->nmcd.dwDrawStage)
	{
	case CDDS_PREPAINT :
		{
			*pResult = CDRF_NOTIFYITEMDRAW;
			return;
		}
		// Modify item text and or background
	case CDDS_ITEMPREPAINT:
		{
			lplvcd->clrText = RGB(0,0,0);
			// If you want the sub items the same as the item,
			// set *pResult to CDRF_NEWFONT
			*pResult = CDRF_NOTIFYSUBITEMDRAW;
			return;
		}
		// Modify sub item text and/or background
	case CDDS_SUBITEM | CDDS_PREPAINT | CDDS_ITEM:
		{
			if(iRow %2){
				lplvcd->clrTextBk = m_colRow2;
			}
			else{
				lplvcd->clrTextBk = m_colRow1;
			}
			
			*pResult = CDRF_DODEFAULT;
			return;
		}
	}
}

6.檢視效果