I'm looking to change the brightness of displays by using the Windows API through the ctypes module in Python. Everything is working as expected until it comes to passing HANDLEs to the GetMonitorBrightness function:
from ctypes import *
from ctypes.wintypes import *
userlib = windll.User32
#Structure to retrieve physical monitors from HMONITOR handle
class PHYSICAL_MONITOR(Structure):
_fields_ = [("handle", HANDLE),
("desc", WCHAR * 128)]
#Get the HMONITOR structure
ForegroundWindow = HWND(windll.User32.GetForegroundWindow())
PrimaryMonitor = HMONITOR(windll.User32.MonitorFromWindow(ForegroundWindow, c_int(1)))
print(PrimaryMonitor)
num_monitors = DWORD()
if windll.Dxva2.GetNumberOfPhysicalMonitorsFromHMONITOR(PrimaryMonitor, byref(num_monitors)):
monitor_array = (PHYSICAL_MONITOR * num_monitors.value)()
cast(monitor_array, POINTER(PHYSICAL_MONITOR))
if windll.Dxva2.GetPhysicalMonitorsFromHMONITOR(PrimaryMonitor, num_monitors, monitor_array):
#num_monitors is 1 in my case: Testing on the only monitor
monitor = HANDLE(monitor_array[0].handle)
min_brightness = DWORD()
current_brightness = DWORD()
max_brightness = DWORD()
status = windll.Dxva2.GetMonitorBrightness(monitor, byref(min_brightness),
byref(current_brightness),
byref(max_brightness))
print(status)
And status prints as 0
I suspect that I'm either allocating the array in the wrong way, or arguments are of the wrong type, as the monitor variable seems to always take the value c_void_p(1)
Relevant Documentation:
GetNumberOfPhysicalMonitors: https://docs.microsoft.com/en-us/windows/win32/api/physicalmonitorenumerationapi/nf-physicalmonitorenumerationapi-getnumberofphysicalmonitorsfromhmonitor
Physical Monitor structure: https://docs.microsoft.com/en-us/windows/win32/api/physicalmonitorenumerationapi/ns-physicalmonitorenumerationapi-physical_monitor
GetPhysicalMonitorsFromHMONITOR: https://docs.microsoft.com/en-us/windows/win32/api/physicalmonitorenumerationapi/nf-physicalmonitorenumerationapi-getphysicalmonitorsfromhmonitor
GetMonitorBrightness: https://docs.microsoft.com/en-us/windows/win32/api/highlevelmonitorconfigurationapi/nf-highlevelmonitorconfigurationapi-getmonitorbrightness