Easy way to calculate text width!! no matter what font

new topic     » topic index » view thread      » older message » newer message

i have just encountered some MFC C++ code that will save a few pple the
hassle of finding text width. here is the routine;

static int _CalcTextWidth(const CString& strText)
{
 CWindowDC dc(NULL);
 CRect rcText(0, 0, 0, 0);
 CFont* pOldFont = dc.SelectObject(&_fontHorzMenu);
 dc.DrawText(strText, &rcText, DT_SINGLELINE | DT_CALCRECT);
 dc.SelectObject(pOldFont);

 return rcText.Width();
}

What is basically happening is that the RECT structure is passed to the
drawText() function with null values for all its elements. The drawText()
function, on noticing this fills the structure with the text width. It
calculates the width based on the font currently selected in the DC.

I Hope this helps those out there who have once had to calculate text width
the difficult way.

Jordah

new topic     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu