How to detect scale factor in Windows 10 in C++

Azeem Cv 1 Reputation point
2022-05-23T06:55:03.21+00:00

I am trying to detect the display scale factor in Windows 10 in C++. Below is the code I am using.

//Code to detect scale
void getDisplayScale(double &h_Scale, double &v_Scale)
{
    //auto activeWindow = GetActiveWindow();
    HWND activeWindow = GetDesktopWindow();
    HMONITOR monitor = MonitorFromWindow(activeWindow, MONITOR_DEFAULTTONEAREST);

    // Get the logical width and height of the monitor
    MONITORINFOEX monitorInfoEx;
    monitorInfoEx.cbSize = sizeof(monitorInfoEx);
    GetMonitorInfo(monitor, &monitorInfoEx);
    long cxLogical = monitorInfoEx.rcMonitor.right - monitorInfoEx.rcMonitor.left;
    long 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);
    DWORD cxPhysical = devMode.dmPelsWidth;
    DWORD cyPhysical = devMode.dmPelsHeight;

    // Calculate the scaling factor
    h_Scale = ((double)cxPhysical / (double)cxLogical);
    v_Scale = ((double)cyPhysical / (double)cyLogical);

    // Round off to 2 decimal places
    h_Scale = round(h_Scale * 100.0) / 100.0;
    v_Scale = round(v_Scale * 100.0) / 100.0;

    std::cout << "Horizonzal scaling: " << h_Scale << "\n";
    std::cout << "Vertical scaling: " << v_Scale;
}

It works properly as a standalone console project.

When I try to put in my MFC code, it returns 100% only. Even if the scale is 125%, it returns 100% only.

How to fix this?

Thanks

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,420 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,526 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 81,636 Reputation points
    2022-05-23T08:26:38.677+00:00

    An usual way is with GetDpiForWindow and a Manifest
    (100% : 96, 125% : 120, 150% : 144, etc...)

    1 person found this answer helpful.