开发者

MFC string width without CDC

开发者 https://www.devze.com 2023-04-03 19:03 出处:网络
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 orde

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 cra开发者_如何学Csh. 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.


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)).


how can you calculate the width if you do not know the font you need to use?

I would suggest to calculate the width in the place, where you see the device context you need and pass it to the class, where you need this width.

0

精彩评论

暂无评论...
验证码 换一张
取 消