c++ - Querying Windows display scaling
问题描述
I want to query the Windows
display scaling setting programmatically:
In this case, I want it to return 125
since I configured my display to be at 125%
scaling. According to this article, the following Windows API C++
code can be used:
// Get desktop dc
desktopDc = GetDC(NULL);
// Get native resolution
horizontalDPI = GetDeviceCaps(desktopDc,LOGPIXELSX);
verticalDPI = GetDeviceCaps(desktopDc,LOGPIXELSY);
However, this code always return 96
and 96
for the horizontal as well as vertical DPI
which translates to 100%
scaling (according to the provided table):
This output is wrong since I still get the same result with 125%
scaling. How can it be done? I'm programming in Java
so I can execute C++
using JNA
. Windows API
solutions are preferred but everything else like a .bat
script or registry
query is also fine as long as it's reliable for all Windows
versions from 7
to 10
.
解决方案
This answer solved it:
#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;
}
推荐阅读
- node.js - 如何只返回一部分数据?
- laravel - MacOs、Docker-sync、Laravel 5.8、Postman - 性能
- sass - 没有 CSS 的源图
- java - 在调用 ihe.iti.xds_b._2007.DocumentRepositoryService 对象的 getDocumentRepositoryPortSoap12 方法时,不能将 JaxbAccessorF_value 强制转换为...
- jquery - Bootstrap 4 升级后没有样式
- ruby-on-rails - Rails - 迁移不会引发错误,但也不会执行所需的迁移
- python - Pandas 是否有办法仅针对特定日期进行基于时间的聚合?
- scala - 将失败的 future 的异常映射到 Some,但 isDefined 不起作用
- javascript - 如何正确使用按键事件
- python - 从另一个 GroupBy 对象创建一个 GroupBy 对象