Using DEFAULT_GUI_FONT in high DPI Windows application

女生的网名这么多〃 提交于 2020-06-29 11:25:23

问题


I have a Windows application which I want to look good at high DPI monitors. The application is using DEFAULT_GUI_FONT in lots of places, and the font created this way doesn't scale correctly.

Is there any simple way to fix this problem with not too much pain?


回答1:


you need get NONCLIENTMETRICS by SystemParametersInfo(SPI_GETNONCLIENTMETRICS,) and then use it LOGFONT data, for create self font. or you can query for SystemParametersInfo(SPI_GETICONTITLELOGFONT) and use it




回答2:


The recommended fonts for different purposes can be obtained from the NONCLIENTMETRICS structure.

For automatically DPI-scaled fonts (Windows 10 1607+, must be per-monitor DPI-aware):

// Your window's handle
HWND window;

// Get the DPI for which your window should scale to
UINT dpi = GetDpiForWindow(window);

// Obtain the recommended fonts, which are already correctly scaled for the current DPI
NONCLIENTMETRICSW non_client_metrics;

if (!SystemParametersInfoForDpi(SPI_GETNONCLIENTMETRICS, sizeof(non_client_metrics), &non_client_metrics, 0, dpi)
{
    // Error handling
}

// Create an appropriate font(s)
HFONT message_font = CreateFontIndirectW(&non_client_metrics.lfMessageFont);

if (!message_font)
{
    // Error handling
}

For older Windows versions you can use the system-wide DPI and scale the font manually (Windows 7+, must be system DPI-aware):

// Your window's handle
HWND window;

// Obtain the recommended fonts, which are already correctly scaled for the current DPI
NONCLIENTMETRICSW non_client_metrics;

if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(non_client_metrics), &non_client_metrics, 0)
{
    // Error handling
}

// Get the system-wide DPI
HDC hdc = GetDC(nullptr);

if (!hdc)
{
    // Error handling
}

UINT dpi = GetDeviceCaps(hdc, LOGPIXELSY);

ReleaseDC(nullptr, hdc);

// Scale the font(s)
constexpr UINT font_size = 12;

non_client_metrics.lfMessageFont.lfHeight = -((font_size * dpi) / 72);

// Create the appropriate font(s)
HFONT message_font = CreateFontIndirectW(&non_client_metrics.lfMessageFont);

if (!message_font)
{
    // Error handling
}

NONCLIENTMETRICS has also many other fonts in it. Make sure to choose the right one for your purpose.

You should set the DPI-awareness level in your application manifest as described here for best compatibility.



来源:https://stackoverflow.com/questions/40340580/using-default-gui-font-in-high-dpi-windows-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!