查询Windows显示缩放比例

Bul*_*aza 3 c++ windows winapi

我想Windows以编程方式查询显示缩放设置: 在这种情况下,我希望它返回,125因为我将显示配置为125%缩放。根据这篇Windows API C++文章,可以使用以下代码:

// Get desktop dc
desktopDc = GetDC(NULL);
// Get native resolution
horizontalDPI = GetDeviceCaps(desktopDc,LOGPIXELSX);
verticalDPI = GetDeviceCaps(desktopDc,LOGPIXELSY);
Run Code Online (Sandbox Code Playgroud)

但是,此代码始终返回96and96对于水平和垂直DPI,这会转换为100%缩放(根据提供的表):

这个输出是错误的,因为我通过缩放仍然得到相同的结果125%。如何做呢?我正在编程,Java以便我可以C++使用JNA. Windows API解决方案是首选,但其他一切(例如.bat脚本或registry查询)也可以,只要它对于从到 的所有Windows版本都是可靠的。710

Bul*_*aza 5

这个答案解决了这个问题:

#include "pch.h"
#include <iostream>
#include <windows.h>

int main()
{
    auto activeWindow = GetActiveWindow();
    HMONITOR monitor = MonitorFromWindow(activeWindow, MONITOR_DEFAULTTONEAREST);

    // Get the logical width and height of the monitor
    MONITORINFOEX monitorInfoEx;
    monitorInfoEx.cbSize = sizeof(monitorInfoEx);
    GetMonitorInfo(monitor, &monitorInfoEx);
    auto cxLogical = monitorInfoEx.rcMonitor.right - monitorInfoEx.rcMonitor.left;
    auto cyLogical = monitorInfoEx.rcMonitor.bottom - monitorInfoEx.rcMonitor.top;

    // Get the physical width and height of the monitor
    DEVMODE devMode;
    devMode.dmSize = sizeof(devMode);
    devMode.dmDriverExtra = 0;
    EnumDisplaySettings(monitorInfoEx.szDevice, ENUM_CURRENT_SETTINGS, &devMode);
    auto cxPhysical = devMode.dmPelsWidth;
    auto cyPhysical = devMode.dmPelsHeight;

    // Calculate the scaling factor
    auto horizontalScale = ((double) cxPhysical / (double) cxLogical);
    auto verticalScale = ((double) cyPhysical / (double) cyLogical);

    std::cout << "Horizonzal scaling: " << horizontalScale << "\n";
    std::cout << "Vertical scaling: " << verticalScale;
}
Run Code Online (Sandbox Code Playgroud)

  • 有一些违反直觉的事情:当我首先在 main 中调用 `SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);` 时,它会报告所有监视器的因子 1.0。如果不这样做,这些因素将与控制面板中显示的每台显示器的因素相匹配。 (2认同)