A Journey 2 Eternity

Posts Tagged ‘Draw Multi-line Text

DT_WORDBREAK and DT_VCENTER flag never work together. So here is an alternative.

void CEMCHotButton::DrawCaption (CDC* pDC, LPDRAWITEMSTRUCT lpDrawItemStruct, CRect& rectCaption, DWORD dwFormat) 
{
	// Get caption text
	CString strCaption;
	GetWindowText (strCaption);

	if(!strCaption.IsEmpty()) {
		if((GetStyle() & BS_MULTILINE) == BS_MULTILINE) {
			dwFormat &= ~DT_SINGLELINE;
			dwFormat &= ~DT_VCENTER;
			dwFormat |= DT_WORDBREAK;

			RECT rct = rectCaption;
			int height = ::DrawText(pDC->m_hDC, (LPCTSTR) strCaption, strCaption.GetLength(), &rct, DT_CALCRECT | DT_WORDBREAK);
			rectCaption.top = rectCaption.CenterPoint().y – height / 2;

			::DrawTextEx (pDC->m_hDC, strCaption.GetBuffer(0), strCaption.GetLength(), &rectCaption, dwFormat, NULL);
		}
	}
}
Advertisements
/*
 * Draw multiline text into a window
 *
 * pDC : Specifies the device context
 * str : Specifies the string
 * rectText : Specifies the text rectangle
 * nFirstVisibleLineIndex : Specifies the first visible line index
 * nFormat : Specifies the method of formatting the text
 */

void CEMCHotCtrl::DrawMultilineText(CDC* pDC, CString str, CRect rectText, int nFirstVisibleLineIndex, int nFormat)
{
	if(str.GetLength() > 0) {
		const TCHAR* p = (LPCTSTR) str;
		CSize sz = pDC->GetTextExtent(p);
		const TCHAR* end = p;
		int nLine = 0;

		if(nFirstVisibleLineIndex > 0) {
			while(*end != 0) {
				if(*end == _T(‘\n’)) {
					nLine++;
					if(nLine == nFirstVisibleLineIndex) {
						end++;
						break;
					}
				}
				end++;
			}
		}

		int len = 0;
		TCHAR buf[10000];

		while(*end != 0) {
			buf[len] = *end;
			end++;
			len++;

			if(*end == _T(‘\n’) || (*end == 0)) {
				if(buf[len - 1] == _T(‘\r’)) {
					buf[len - 1] = 0;
				}

				buf[len] = 0;
				pDC->DrawText(buf, -1, rectText, nFormat);

				if(*end == _T(‘\n’)) {
					end++;
				}

				rectText.top += sz.cy;
				len = 0;
			}
		}
	}
}

Pages

Categories

June 2018
M T W T F S S
« Aug    
 123
45678910
11121314151617
18192021222324
252627282930  

Blog Stats

  • 28,495 hits
Advertisements