- 1 year ago
How to know the status of monitor is on or off in python?
Comment
1 / 1
To determine the status of a monitor (whether it is on or off) in Python, you can use the ctypes
module to interact with the Windows API. Here's an example:
pythonimport ctypes
def is_monitor_on():
user32 = ctypes.windll.user32
SM_CMONITORS = 80
# Get the number of monitors in the system
num_monitors = user32.GetSystemMetrics(SM_CMONITORS)
# Iterate over each monitor and check its status
for i in range(num_monitors):
monitor_info = ctypes.create_string_buffer(32)
monitor_info.cbSize = ctypes.sizeof(monitor_info)
# Get the monitor information
success = user32.GetMonitorInfoW(user32.MonitorFromIndex(i), ctypes.byref(monitor_info))
if success:
state = monitor_info.dwFlags & 1
if state == 1:
return True # Monitor is on
return False # No active monitors found
# Example usage
monitor_status = is_monitor_on()
print("Monitor is on" if monitor_status else "Monitor is off")
In this example, the is_monitor_on
function determines the status of each monitor in the system by retrieving monitor information using the GetMonitorInfoW
function from the Windows API. The function checks the dwFlags
attribute of the monitor information structure to determine if the monitor is on or off.
Please note that this solution is specific to Windows and relies on the Windows API. It may not work on other operating systems. Additionally, you may need to adjust the code or handle potential exceptions based on your specific requirements and environment.