- 1 year ago
How to detect native screen resolution or scaling factor of the secondary monitor at Windows 10
Comment
1 / 1
To detect the native screen resolution and scaling factor of a secondary monitor on Windows 10, you can use the EnumDisplaySettingsEx
and GetDpiForMonitor
functions from the Windows API. Here's a step-by-step guide on how to achieve this in Python using the ctypes
module to call the Windows API functions:
- Install the
pywin32
module if you haven't already. This module provides Python bindings for the Windows API and will help us call the necessary functions.
bashpip install pywin32
- Create a Python script with the following code:
pythonimport ctypes
from ctypes import wintypes
# Constants for API functions
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32
# EnumDisplaySettingsEx
ENUM_CURRENT_SETTINGS = -1
ENUM_REGISTRY_SETTINGS = -2
CCHDEVICENAME = 32
# MONITORINFOEX
class MONITORINFOEX(ctypes.Structure):
_fields_ = [
('cbSize', wintypes.DWORD),
('rcMonitor', wintypes.RECT),
('rcWork', wintypes.RECT),
('dwFlags', wintypes.DWORD),
('szDevice', wintypes.WCHAR * CCHDEVICENAME)
]
# GetDpiForMonitor
PROCESS_PER_MONITOR_DPI_AWARE = 2
def get_native_resolution_and_scaling_factor(monitor_index=1):
# Get the monitor handle
monitor_handles = [user32.MonitorFromPoint((0, 0), 2), user32.MonitorFromPoint((0, 0), 1)]
monitor_handle = monitor_handles[monitor_index]
# Get the monitor info
monitor_info = MONITORINFOEX()
monitor_info.cbSize = ctypes.sizeof(MONITORINFOEX)
user32.GetMonitorInfoW(monitor_handle, ctypes.byref(monitor_info))
# Get the display settings
display_settings = wintypes.DEVMODE()
display_settings.dmSize = ctypes.sizeof(wintypes.DEVMODE)
gdi32.EnumDisplaySettingsExW(monitor_info.szDevice, ENUM_CURRENT_SETTINGS, ctypes.byref(display_settings), 0)
# Get the DPI for the monitor
dpi_x = ctypes.c_ulong()
dpi_y = ctypes.c_ulong()
user32.GetDpiForMonitor(monitor_handle, PROCESS_PER_MONITOR_DPI_AWARE, ctypes.byref(dpi_x), ctypes.byref(dpi_y))
return (
(display_settings.dmPelsWidth, display_settings.dmPelsHeight),
(dpi_x.value, dpi_y.value)
)
if __name__ == "__main__":
primary_resolution, primary_scaling_factor = get_native_resolution_and_scaling_factor(0)
secondary_resolution, secondary_scaling_factor = get_native_resolution_and_scaling_factor(1)
print(f"Primary Monitor:")
print(f"Resolution: {primary_resolution[0]}x{primary_resolution[1]}")
print(f"Scaling Factor: {primary_scaling_factor}")
print(f"\nSecondary Monitor:")
print(f"Resolution: {secondary_resolution[0]}x{secondary_resolution[1]}")
print(f"Scaling Factor: {secondary_scaling_factor}")
This script will output the native resolution and scaling factor for both the primary and secondary monitors on your Windows 10 system.
Note: The pywin32
module provides Python bindings for a wide range of Windows API functions. Make sure to use it responsibly and handle exceptions appropriately in case of any errors while calling the API functions.