Custom drawing of a CTreeCtrl to support dark mode and text color properties

ChuckieAJ 201 Reputation points
2025-02-06T11:59:28.5666667+00:00

I have added a CTreeCtrl to my CDialogEx and mapped it to a CDarkModeTreeCtrl variable. In my dialogs OnInitInstance I set the background colour of the tree control:

m_treeCtrl.SetBkColor(DarkModeTools::darkBkControlColor);

I would ideally like to set this automatically in my derived class.

The derived class handles the NM_CUSTOMDRAW message:

void CDarkModeTreeCtrl::OnNMCustomdraw(NMHDR* pNMHDR, LRESULT* pResult)
{
	LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
	*pResult = CDRF_DODEFAULT;
	return; // Return early and bypass
	switch (pNMCD->dwDrawStage)
	{
	case CDDS_PREPAINT:
		*pResult = CDRF_NOTIFYITEMDRAW;
		break;
	case CDDS_ITEMPREPAINT:
	{
		CDC* pDC = CDC::FromHandle(pNMCD->hdc);
		if (pDC)
		{
			// Set text and background color
			pDC->SetTextColor(DarkModeTools::darkTextColor);
			CRect rcItem;
			GetItemRect((HTREEITEM)pNMCD->dwItemSpec, &rcItem, TRUE);
			pDC->FillSolidRect(rcItem, DarkModeTools::darkBkControlColor);
			// Draw the text manually
			CString strText = GetItemText((HTREEITEM)pNMCD->dwItemSpec);
			pDC->DrawText(strText, &rcItem, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
		}
		 *pResult = CDRF_SKIPDEFAULT; // Skip default drawing
		break;
	}
	default:
		break;
	}
}

At the moment I am returning early, so it looks like this:

User's image

Looks great!, But the text is dark. When I comment out the early return statement, so that it runs my content, I end up with:

User's image

I have lost the buttons and lines and focused item etc. Doesn't work properly.

All I want to do here is set the text color properties. The drawing would ideally be done by the theme.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,856 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. ChuckieAJ 201 Reputation points
    2025-02-06T12:05:28.2333333+00:00

    ROTFL!

    I did not need to derived from CTreeCtrl afterall!

    m_treeCtrl.SetTextColor(DarkModeTools::darkTextColor);
    

    Sorted!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.