Skip to content

Instantly share code, notes, and snippets.

@matthewnitschke
Created April 15, 2025 02:33
Show Gist options
  • Select an option

  • Save matthewnitschke/4d0b132731b3b58464467abc97c09c41 to your computer and use it in GitHub Desktop.

Select an option

Save matthewnitschke/4d0b132731b3b58464467abc97c09c41 to your computer and use it in GitHub Desktop.
Enable/Disable/List MacOS displays
#!/usr/bin/env python3
from ctypes import (CDLL, util, c_void_p, c_uint32, c_int, c_bool, POINTER, byref)
import time
cg = CDLL(util.find_library('CoreGraphics'))
cg.CGBeginDisplayConfiguration.argtypes = [POINTER(c_void_p)]
cg.CGBeginDisplayConfiguration.restype = c_int
cg.CGCompleteDisplayConfiguration.argtypes = [c_void_p, c_int]
cg.CGCompleteDisplayConfiguration.restype = c_int
cg.CGCancelDisplayConfiguration.argtypes = [c_void_p]
cg.CGCancelDisplayConfiguration.restype = c_int
cg.CGSConfigureDisplayEnabled.argtypes = [c_void_p, c_uint32, c_bool]
cg.CGSConfigureDisplayEnabled.restype = c_int
cg.CGGetActiveDisplayList.argtypes = [c_int, POINTER(c_int), POINTER(c_int)]
cg.CGGetActiveDisplayList.restype = c_int
def enable_display(display_id):
config_ref = c_void_p()
if cg.CGBeginDisplayConfiguration(byref(config_ref)) != 0:
return
if cg.CGSConfigureDisplayEnabled:
if cg.CGSConfigureDisplayEnabled(config_ref, display_id, True) != 0:
cg.CGCancelDisplayConfiguration(config_ref)
return
cg.CGCompleteDisplayConfiguration(config_ref, 0)
def disable_display(display_id):
config_ref = c_void_p()
if cg.CGBeginDisplayConfiguration(byref(config_ref)) != 0:
return
if cg.CGSConfigureDisplayEnabled:
if cg.CGSConfigureDisplayEnabled(config_ref, display_id, False) != 0:
cg.CGCancelDisplayConfiguration(config_ref)
return
cg.CGCompleteDisplayConfiguration(config_ref, 0)
def get_active_displays():
display_count = c_int()
if cg.CGGetActiveDisplayList(c_int(0), None, byref(display_count)) != 0:
return
displays = (c_int * display_count.value)()
if cg.CGGetActiveDisplayList(display_count, displays, byref(display_count)) != 0:
return
return [displays[i] for i in range(display_count.value)]
if __name__ == "__main__":
displays = get_active_displays()
for display in displays:
print("Disabling Display: " + str(display))
disable_display(display)
time.sleep(2)
for display in displays:
print("Enabling Display: " + str(display))
enable_display(display)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment