Click here to Skip to main content
15,881,882 members
Articles / Desktop Programming / WTL

Owner Drawn ListViews In WTL

Rate me:
Please Sign up or sign in to vote.
4.65/5 (13 votes)
26 Jun 20043 min read 71.5K   4.4K   34  
An overview of handling owner drawn listview controls in WTL.
#include "stdafx.h"
#include ".\demoownerdrawnlistviewctrl.h"

void CDemoOwnerDrawnListViewCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	HDC dc = lpDrawItemStruct->hDC;
	CRect item_rect = lpDrawItemStruct->rcItem;
	int item_id = lpDrawItemStruct->itemID;

	bool checkered_toggle = (item_id % 2) != 0;
	int cols = GetHeader().GetItemCount();
	for(int n = 0; n < cols; n++)
	{
		CRect cell_rect;
		GetCellRect(n, item_rect, cell_rect);

		COLORREF square_color;

		if(lpDrawItemStruct->itemState & ODS_SELECTED)
		{
			square_color = GetSysColor(COLOR_HIGHLIGHT);
			::SetTextColor(dc, GetSysColor(COLOR_HIGHLIGHTTEXT));
		}
		else
		{
			square_color = 
				checkered_toggle ? RGB(230, 244, 255) : RGB(145, 200, 255);	
			::SetTextColor(dc, GetSysColor(COLOR_BTNTEXT));
		}

		HPEN square_pen = CreatePen(PS_SOLID, 1, square_color);
		HBRUSH squares_brush = CreateSolidBrush(square_color);
		SelectObject(dc, square_pen);
		SelectObject(dc, squares_brush);
		Rectangle(dc, cell_rect.left, cell_rect.top, 
					cell_rect.right, cell_rect.bottom);
		DeleteObject(square_pen);
		DeleteObject(squares_brush);
		
		std::stringstream ss;
		ss << item_id << _T(":") << n;

		DrawText(dc, ss.str().c_str(), ss.str().size(), cell_rect, 
					DT_CENTER | DT_END_ELLIPSIS | DT_VCENTER | DT_SINGLELINE);

		checkered_toggle = !checkered_toggle;
	}
}

void CDemoOwnerDrawnListViewCtrl::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
	CClientDC dc(m_hWnd);
	TEXTMETRIC tm;

	dc.SelectFont(GetFont());
	dc.GetTextMetrics(&tm);

	lpMeasureItemStruct->itemHeight = 
		(tm.tmHeight + tm.tmExternalLeading) * 2;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions