- 1 year ago
Query Windows 10/8 Monitor Scaling from Python Script?
To query the monitor scaling (DPI scaling) on Windows 10/8 from a Python script, you can use the ctypes
library to access the Windows API. Specifically, you can use the GetDpiForMonitor
function to get the DPI scaling for a particular monitor.
Here's an example Python script that demonstrates how to do this:
pythonimport ctypes
# Define the required Windows API functions and structures using ctypes
user32 = ctypes.windll.user32
class RECT(ctypes.Structure):
_fields_ = [("left", ctypes.c_long),
("top", ctypes.c_long),
("right", ctypes.c_long),
("bottom", ctypes.c_long)]
class MONITORINFO(ctypes.Structure):
_fields_ = [("cbSize", ctypes.c_uint),
("rcMonitor", RECT),
("rcWork", RECT),
("dwFlags", ctypes.c_uint)]
def get_dpi_scaling():
# Get the handle to the primary monitor
hMonitor = user32.MonitorFromWindow(0, 1) # MONITOR_DEFAULTTOPRIMARY = 1
# Initialize the MONITORINFO structure
monitor_info = MONITORINFO()
monitor_info.cbSize = ctypes.sizeof(MONITORINFO)
# Get monitor information, including DPI scaling
success = user32.GetMonitorInfoW(hMonitor, ctypes.byref(monitor_info))
if not success:
raise OSError("Failed to get monitor info")
# Extract the DPI scaling value
dpi_x = user32.GetDpiForMonitor(hMonitor, 0)
dpi_y = user32.GetDpiForMonitor(hMonitor, 1)
return dpi_x, dpi_y
if __name__ == "__main__":
dpi_x, dpi_y = get_dpi_scaling()
print(f"DPI Scaling (X): {dpi_x}")
print(f"DPI Scaling (Y): {dpi_y}")
Save this script to a .py
file and run it using Python. The script will print the DPI scaling values for the primary monitor (X and Y directions).
Note: This script uses the Windows API, and it will work on Windows 10/8. It may not work on other operating systems. Additionally, this example only queries the DPI scaling for the primary monitor. If you need to query DPI scaling for multiple monitors, you can modify the script to enumerate all monitors using EnumDisplayMonitors
function.