This project provides a native Python script to toggle the orientation of a secondary monitor (landscape/portrait) on a Windows environment via a keyboard shortcut.
- Zero third-party dependencies: Exclusive use of the standard
ctypeslibrary to interact directly with the Windows API (user32.dll). - Broad compatibility: Operational on both stable and development versions of Python 3.x (tested on 3.15.0a5).
- Silent execution: Using the
.pywextension ensures background execution without instantiating a console window.
- Operating System: Windows (10, 11).
- Python 3.x interpreter.
- Hardware configuration: At least two connected monitors recognized by the system.
- Download
screen_rotation.pyw - Place the file in a permanent system directory.
A Python 3.x interpreter is required to execute this script on Windows.
-
Navigate to the official Python distribution page:
https://www.python.org/downloads/windows/ -
Download the Windows installer for the latest stable release (64-bit).
-
Execute the downloaded installer.
-
Critical Step: On the initial setup interface, explicitly check the box labeled Add Python 3.x to PATH at the bottom of the window before proceeding.
-
Click Install Now and allow the process to complete.
For environments requiring multiple Python versions, pyenv-win can be utilized.
- Install
pyenv-winvia PowerShell:Invoke-WebRequest -UseBasicParsing -Uri "[https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1](https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1)" -OutFile "./install-pyenv-win.ps1"; &"./install-pyenv-win.ps1"
Assigning a key combination requires creating an intermediate system shortcut.
- Right-click the
screen_rotation.pywfile and select Create shortcut. - Move this shortcut to an accessible location (e.g., the Desktop).
- Open the shortcut's Properties (Right-click > Properties).
- In the Shortcut tab, modify the Target field to use the GUI-less Python executable (
pythonw.exe), followed by the absolute path to the script.- Syntax:
C:\Path\To\pythonw.exe "C:\Path\To\screen_rotation.pyw"
- Syntax:
- Select the Shortcut key field and execute the desired physical key combination on the keyboard (e.g., Ctrl + Alt + F12).
- Validate by clicking Apply then OK.
EnumDisplayDevicesW: Identifies active displays and isolates the hardware identifier of the secondary monitor.EnumDisplaySettingsW: Extracts theDEVMODEWstructure containing the current resolution and orientation parameters of the target monitor.ChangeDisplaySettingsExW: Applies the new orientation (0 or 90 degrees), inverts the resolution axes (width/height), and forces a Windows registry update (CDS_UPDATEREGISTRY).