Displaying text on a Toolbar

This article was contributed by Michael Brannan.

Here is a little bit of code for adding text to your toolbars. In the sample there is a CToolBar derived class that overrides LoadToolBar(...) and adds the text to the toolbar according to the command id of the button. The text added in the example is the last line of text from the resource string whose id is the same as the command id of the button. So for ID_FILE_NEW we have the standard string "Create a new document\nNew" which would give us a button text of "New" where as if we change ID_FILE_NEW to "Create a new document\nNew\nNew File" this will cause "New File" to be displayed on the toolbar button.

After the button text has been added the buttons are resized so that you can see the text proplerly. The main code for this is as follows:

BOOL CTextToolBar::LoadToolBar(LPCTSTR lpszResourceName)
	BOOL bReturn = CToolBar::LoadToolBar(lpszResourceName);

	// Check if we loaded the toolbar.
	if (bReturn == FALSE)
		return bReturn;

	// Make it flat.
	ModifyStyle(0, GetStyle()|TBSTYLE_FLAT);

	// Set the text for each button
	CToolBarCtrl& bar = GetToolBarCtrl();

	// Remove the string map in case we are loading another toolbar into this control
	if (m_pStringMap)
		delete m_pStringMap;
		m_pStringMap = NULL;

	int		nIndex = 0;

	for (nIndex = bar.GetButtonCount() - 1; nIndex >= 0; nIndex--)
		ZeroMemory(&tb, sizeof(TBBUTTON));
		bar.GetButton(nIndex, &tb);

		// Do we have a separator?
		if ((tb.fsStyle & TBSTYLE_SEP) ==  TBSTYLE_SEP)

		// Have we got a valid command id?
		if (tb.idCommand == 0)

		// Get the resource string if there is one.
		CString strText;
		LPCTSTR lpszButtonText = NULL;
		CString	strButtonText(_T(""));
		_TCHAR	seps[] = _T("\n");


		if (!strText.IsEmpty())
			lpszButtonText = _tcstok((LPTSTR)(LPCTSTR)strText, seps);

				strButtonText = lpszButtonText;
				lpszButtonText = _tcstok(NULL, seps);

		if (!strButtonText.IsEmpty())
			SetButtonText(nIndex, strButtonText);

	// Resize the buttons so that the text will fit.
	CRect rc(0, 0, 0, 0);
	CSize sizeMax(0, 0);

	for (nIndex = bar.GetButtonCount() - 1; nIndex >= 0; nIndex--)
		bar.GetItemRect(nIndex, rc);

		sizeMax.cx = __max(rc.Size().cx, sizeMax.cx);
		sizeMax.cy = __max(rc.Size().cy, sizeMax.cy);
	SetSizes(sizeMax, CSize(16,15));

	return bReturn;

Last updated: 4 December 1998