简体   繁体   English

GetTextExtentPoint32不考虑当前字体

[英]GetTextExtentPoint32 Doesn't Take Account of the Current Font

I need to find the width of a string with any font. 我需要找到任何字体的字符串的宽度。 However, when I use GetTextExtentPoint32 , it doesn't take the account of the current font. 但是,当我使用GetTextExtentPoint32 ,它不会考虑当前字体。 This is my code: 这是我的代码:

HFONT hFont = CreateFont(36, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, 
    OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, NULL);

SelectObject(GetDC(m_hSettingsWnd), hFont);
GetTextExtentPoint32(GetDC(m_hSettingsWnd), TITLE_TEXT, wcslen(TITLE_TEXT), &sTextSize);
// TITLE_TEXT is the string I'm trying to get the width of.

Could anybody correct the formatting as well, please? 任何人也可以更正格式吗? I'm new to Stack Overflow and the code sample isn't working properly for me. 我是Stack Overflow的新手,并且代码示例对我来说无法正常工作。

SelectObject(GetDC(m_hSettingsWnd), ...);
GetTextExtentPoint32(GetDC(m_hSettingsWnd), ...);

By using GetDC() in that manner, you are creating resource leaks. 通过以这种方式使用GetDC() ,您正在创建资源泄漏。 Each call to GetDC() must be followed by a call to ReleaseDC() . 每个对GetDC()的调用都必须在对ReleaseDC()的调用之后。 And each call to GetDC() creates a separate HDC , which is why GetTextExtentPoint32() does not know about your font, as you have not selected it into that second HDC . 而且每次对GetDC()调用都会创建一个单独的HDC ,这就是为什么GetTextExtentPoint32()不知道您的字体的原因,因为您没有将其选择到第二个HDC

Correct usage of GetDC() should fix the font problem. 正确使用GetDC()应该可以解决字体问题。 Make sure to also restore the old font before you free the HDC : 释放HDC之前,请确保还恢复了旧字体:

HDC hdc = GetDC(hwnd);
const wchar_t *buf = L"buf";
HFONT hFont = CreateFont(36, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, 
    OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, NULL);

SIZE size;
HFONT oldfont = (HFONT) SelectObject(hdc, hFont);
GetTextExtentPoint32(hdc, buf, wcslen(buf), &size);

SelectObject(hdc, oldfont);
DeleteObject(hFont);

ReleaseDC(hwnd, hdc);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM