r/PowerShell • u/Kindly-Information52 • 13h ago
Script Sharing I built MonitorAutoSwitch - automatically moves my laptop display to the correct side of my monitor (home vs office) based on my public IP
The problem: at home my laptop sits to the right of my ultrawide, at the office it sits to the left of the monitor. Windows kept getting confused after docking, so every arrival was alt-tabbing into Display Settings and dragging rectangles around.
What it does: a small PowerShell tool that detects where I am via my public IP and repositions the laptop display on the correct side of the main monitor. Triggers on logon, wake from sleep and display connect, plus a once-a-minute display-count watcher. Comes with a WinForms setup wizard, a system tray toggle, and a per-user installer (no admin rights, everything lives in %LOCALAPPDATA% and Task Scheduler).
The bug that took months: the first version stored absolute coordinates (X=5120) and randomly failed with DISP_CHANGE_FAILED (-1) from ChangeDisplaySettingsEx. Root cause turned out to be two-fold: the monitor sometimes runs at a non-native resolution, and a non-DPI-aware PowerShell process sees scaled coordinates - so the target position landed outside the desktop. The fix: store only "left" or "right" + a Y offset, compute the real X from the live display widths on every run, and opt the process into per-monitor DPI awareness via SetProcessDpiAwarenessContext. Also worth knowing: Windows can hand out high device numbers like \.\DISPLAY13, so don't enumerate only DISPLAY1-9.
GitHub (MIT): https://github.com/dimitrihilverda/MonitorAutoSwitch
Full disclosure: built in pair-programming style with Claude - the design decisions and months of debugging pain are mine, a good chunk of the typing was not. Feedback on the Win32 interop is very welcome.