GetTextExtent vs. DrawText (with DT_CALCRECT)

Working on an MFC app that has just been converted to Unicode (finally!), I noticed that one button (which is created dynamically) is too small to fit the text in Korean (and Russian and a few other languages).

The code was calling something like:

CSize sz = m_btAdjustColors.GetDC()->GetTextExtent(sCaption);

It seems correct, but these script languages are throwing it for a loop–the measured size is much smaller than it should be. The GetTextExtent documentation doesn’t shed any explicit light on this subject, but may hint at it.

The solution? DrawText. There is a flag you can pass to tell it to calculate the rectangle needed instead of drawing.

CRect rect(0,0,0,0);
m_btAdjustColors.GetDC()->DrawText(sCaption, &rect, DT_CALCRECT);

It’s important to initialize the rectangle to zeroes because, as the docs say, it only modifies the right and bottom members of the rectangle.

3 thoughts on “GetTextExtent vs. DrawText (with DT_CALCRECT)

  1. grant bowgen

    I tried using DrawText but it made no difference. However if you select the font first using GetDC->SelectObject(font) for the relevant font, then both GetTextExtent and DrawText work.

  2. gast128

    …yes and be aware that above code leaks a dc, because the dc returns by GetDC must be released unless its a class dc.

Comments are closed.