Dave's Brain

Browse - programming tips - mfc ctreectrl custom colors

Date: 2009sep24
Platform: MFC
Language: C/C++

Q.  What's the best way to have custom colors in my CTreeCtrl ?

A.  Use NN_CUSTOMDRAW like this:

In your .h file put:

	//{{AFX_MSG(CExampleDlg)
	void CExampleDlg::OnCustomDrawTree(NMHDR* pNMHDR, LRESULT* pResult);
	//}}AFX_MSG

In your .cpp file put:

	BEGIN_MESSAGE_MAP(CExampleDlg, CDialog)
	//{{AFX_MSG_MAP(CExampleDlg)
	ON_NOTIFY(NM_CUSTOMDRAW, IDC_TREE, OnCustomDrawTree)	
	//}}AFX_MSG_MAP
	END_MESSAGE_MAP()

and

void CExampleDlg::OnCustomDrawTree(NMHDR* pNMHDR, LRESULT* pResult)
{
	LPNMTVCUSTOMDRAW		tvcd = (LPNMTVCUSTOMDRAW) pNMHDR;

	*pResult = CDRF_DODEFAULT;

	switch(tvcd->nmcd.dwDrawStage)
	{
	case CDDS_PREPAINT:
		*pResult = CDRF_NOTIFYITEMDRAW;
		break;
	case CDDS_ITEMPREPAINT:
		tvcd->clrTextBk = tvcd->nmcd.lItemlParam;
		break;
	}
}

void CExampleDlg::ExampleUse()
{
	m_Tree.SetItemData(3, RGB(0xFF, 0x00, 0x00)); // Make item 3 red
}

You do NOT need to set a parameters in your .rc file for this to work.

Wrong:
This can also be done by setting LVS_OWNERDRAWFIXED in the .rc file
and overridding DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) but that is
much harder.
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: