Search code examples
c++mfcfontmetrics

MFC string width without CDC


Is there any way to get the width of a string in pixels without using CDC or using a CDC not linked with a display. The class that needs to retrieve the string width does not inherit from CWnd in order to use CWnd::GetDC() and there is no way to pass an existing CDC to the function.

I have tried to create a dummy CDC that is not linked with a display, however this causes MFC to crash. Ideally something like:

m_font = new CFont();
m_font->CreatePointFont(size * 10, _T("Arial"));

m_tempCDC = new CDC();
m_tempCDC->SelectObject(m_font);

return m_tempCDC->GetOutputTextExtent(_T("Test")).cx;

EDIT: Should have substituted the font name variable for a string literal.


Solution

  • The width of a font is dependent on how it is converted to pixels, and this is dependent on the device it is being rendered on. It will obviously be different for a printer versus a monitor for example. This is why you need a DC for this function.

    You can get the DC for the desktop using CDC::FromHandle(::GetDC(NULL)).