|
| 1 | +#include <windows.h> |
| 2 | + |
| 3 | +namespace nativeapi { |
| 4 | + |
| 5 | +// Internal: per-monitor DPI via Shcore when available |
| 6 | +static double GetScaleFactorForMonitor(HMONITOR hmonitor) { |
| 7 | + if (!hmonitor) return 1.0; |
| 8 | + typedef HRESULT(WINAPI * GetDpiForMonitorFunc)(HMONITOR, int, UINT*, UINT*); |
| 9 | + static GetDpiForMonitorFunc pGetDpiForMonitor = nullptr; |
| 10 | + static bool resolved = false; |
| 11 | + if (!resolved) { |
| 12 | + HMODULE hShcore = LoadLibraryW(L"Shcore.dll"); |
| 13 | + if (hShcore) { |
| 14 | + pGetDpiForMonitor = reinterpret_cast<GetDpiForMonitorFunc>( |
| 15 | + GetProcAddress(hShcore, "GetDpiForMonitor")); |
| 16 | + } |
| 17 | + resolved = true; |
| 18 | + } |
| 19 | + if (pGetDpiForMonitor) { |
| 20 | + UINT dpiX = 96, dpiY = 96; |
| 21 | + if (SUCCEEDED(pGetDpiForMonitor(hmonitor, 0 /* MDT_EFFECTIVE_DPI */, &dpiX, &dpiY))) { |
| 22 | + return static_cast<double>(dpiX) / 96.0; |
| 23 | + } |
| 24 | + } |
| 25 | + return 1.0; |
| 26 | +} |
| 27 | + |
| 28 | +double GetScaleFactorForWindow(HWND hwnd) { |
| 29 | + if (hwnd) { |
| 30 | + // Prefer GetDpiForWindow if available |
| 31 | + typedef UINT(WINAPI * GetDpiForWindowFunc)(HWND); |
| 32 | + static GetDpiForWindowFunc pGetDpiForWindow = nullptr; |
| 33 | + static bool resolved_win = false; |
| 34 | + if (!resolved_win) { |
| 35 | + HMODULE hUser32 = LoadLibraryW(L"user32.dll"); |
| 36 | + if (hUser32) { |
| 37 | + pGetDpiForWindow = reinterpret_cast<GetDpiForWindowFunc>( |
| 38 | + GetProcAddress(hUser32, "GetDpiForWindow")); |
| 39 | + } |
| 40 | + resolved_win = true; |
| 41 | + } |
| 42 | + if (pGetDpiForWindow) { |
| 43 | + UINT dpi = pGetDpiForWindow(hwnd); |
| 44 | + if (dpi > 0) { |
| 45 | + return static_cast<double>(dpi) / 96.0; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + // Fallback: per-monitor DPI |
| 50 | + HMONITOR hmonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); |
| 51 | + double monitor_scale = GetScaleFactorForMonitor(hmonitor); |
| 52 | + if (monitor_scale > 0.0) return monitor_scale; |
| 53 | + } |
| 54 | + |
| 55 | + // Fallback: system DPI |
| 56 | + HDC hdc = GetDC(nullptr); |
| 57 | + if (hdc) { |
| 58 | + int dpiX = GetDeviceCaps(hdc, LOGPIXELSX); |
| 59 | + ReleaseDC(nullptr, hdc); |
| 60 | + if (dpiX > 0) { |
| 61 | + return static_cast<double>(dpiX) / 96.0; |
| 62 | + } |
| 63 | + } |
| 64 | + return 1.0; |
| 65 | +} |
| 66 | + |
| 67 | +} // namespace nativeapi |
| 68 | + |
| 69 | + |
0 commit comments