import win32api import win32con import time import sys def set_orientation(rotation_val): """ Changes the screen orientation. rotation_val: win32con.DMDO_DEFAULT (0 degrees) win32con.DMDO_90 (90 degrees) win32con.DMDO_180 (180 degrees) win32con.DMDO_270 (270 degrees) """ device = win32api.EnumDisplayDevices(None, 0) devmode = win32api.EnumDisplaySettings(device.DeviceName, win32con.ENUM_CURRENT_SETTINGS) # 1. Get the "Natural" dimensions (Landscape) # Regardless of current rotation, find the long side and short side if devmode.PelsWidth < devmode.PelsHeight: # Currently portrait, so swap to get natural landscape natural_width = devmode.PelsHeight natural_height = devmode.PelsWidth else: # Currently landscape natural_width = devmode.PelsWidth natural_height = devmode.PelsHeight # 2. Set target dimensions based on requested rotation if rotation_val in [win32con.DMDO_90, win32con.DMDO_270]: # Target is Portrait -> Width must be the short side devmode.PelsWidth = natural_height devmode.PelsHeight = natural_width else: # Target is Landscape -> Width must be the long side devmode.PelsWidth = natural_width devmode.PelsHeight = natural_height # 3. Set the orientation devmode.DisplayOrientation = rotation_val # 4. CRITICAL: Tell Windows we are updating Width, Height, AND Orientation # DM_PELSWIDTH (0x80000) | DM_PELSHEIGHT (0x100000) | DM_DISPLAYORIENTATION (0x80) devmode.Fields = devmode.Fields | win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT | win32con.DM_DISPLAYORIENTATION # Apply the settings res = win32api.ChangeDisplaySettingsEx(device.DeviceName, devmode) if res != win32con.DISP_CHANGE_SUCCESSFUL: # Note: Some drivers (Intel/Nvidia) disable 180-degree rotation in their control panel. # If 180 fails but others work, check your graphics driver settings. print(f"Failed to change to val {rotation_val}. Error code: {res}") def main(): print("Starting screen rotation cycle...") print("Press Ctrl+C to stop early (screen will reset).") # Save the original orientation to restore later device = win32api.EnumDisplayDevices(None, 0) original_devmode = win32api.EnumDisplaySettings(device.DeviceName, win32con.ENUM_CURRENT_SETTINGS) original_orientation = original_devmode.DisplayOrientation # The list of orientations to cycle through orientations = [ ("90 Degrees", win32con.DMDO_90), ("180 Degrees", win32con.DMDO_180), ("270 Degrees", win32con.DMDO_270), ("Default (0)", win32con.DMDO_DEFAULT) ] try: # Loop 2 times for i in range(2): for name, val in orientations: print(f"Rotating to: {name}") set_orientation(val) time.sleep(3) except KeyboardInterrupt: print("\nScript interrupted by user.") except Exception as e: print(f"\nAn error occurred: {e}") finally: print("Restoring original orientation...") # Reset using the same robust logic set_orientation(original_orientation) print("Done.") if __name__ == "__main__": main()