r/PowerShell • u/Kindly-Information52 • 1d 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.
2
u/SimpleSysadmin 21h ago
Why not use a unique identifier from the dock itself?
I’m also curious why your computer couldn’t just remember its screen configuration, I’ve found moving between docks and setting config once is enough. Was any time spent trying to figure out why this behaviour was not working?
2
u/Kindly-Information52 20h ago
I it was before I had a dock and then at home the setup looked the same for windows, same laptop same wide screen, only difference is the position of the laptop to the screen. Then Windows has no clue.
1
u/i2apier 20h ago
Reminds me of PersistentWindows
Helped me resolved the issue with unwanted behavior of Windows moving window(s) to main monitor. Not sure if it would have solve your issue though
1
u/Creative-Type9411 21h ago edited 21h ago
do you have statics set at both office and home? what if your outside ip changes?
also, if you DO use AI.. and you used it to write the readme here.. why would you wait months to get through a bug?
hostname might be a better identifier.. also does this work for people with different monitors than yours?