Change background color

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.



Changing the background color of a listview control is very easy if you are
already using an owner drawn control. See
‘Selection highlighting of entire row’

for code on how to implement an owner drawn listview control. Once the basic owner
draw code is in place all you need to do to get a different background color is to
fill the row rectangle with the desired color before drawing the individual elements of the row.

If you are using the implementation shown in
‘Selection highlighting of entire row’
then you can change the code to draw the background color or highlight in the DrawItem() function.
Change the code given below

	// Draw the background color
	if( bHighlight )
	{
		pDC->SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
		pDC->SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));

		pDC->FillRect(rcHighlight, &CBrush(::GetSysColor(COLOR_HIGHLIGHT)));
	}
	else
		pDC->FillRect(rcHighlight, &CBrush(::GetSysColor(COLOR_WINDOW)));

to the following code. This well set the background to yellow.

	// Draw the background color
	if( bHighlight )
	{
		pDC->SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
		pDC->SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));

		pDC->FillRect(rcHighlight, &CBrush(::GetSysColor(COLOR_HIGHLIGHT)));
	}
	else
	{
		CRect rcClient, rcRow = rcItem;
		GetClientRect(&rcClient);
		rcRow.right = rcClient.right;

		pDC->FillRect(rcRow, &CBrush(RGB(255,255,0));
// Remove	pDC->FillRect(rcHighlight, &CBrush(::GetSysColor(COLOR_WINDOW)));
	}

You also have to add a handler for the WM_ERASEBKGND message. This message is sent when the background needs to be painted. This is necessary because the DrawItem() function is called only for list rows. This leaves the area below the last row and to the right of the last column and that’s where the WM_ERASEBKGND handler comes in. Here’s the code.

BOOL CMyListCtrl::OnEraseBkgnd(CDC* pDC)
{
	CRect rcClient;
	GetClientRect( &rcClient );

	pDC->FillRect(rcClient, &CBrush(RGB(255,255,0)));
	return TRUE;
}

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read