Skip to content

Instantly share code, notes, and snippets.

@BoxedBrain
Created April 5, 2024 13:28
Show Gist options
  • Save BoxedBrain/f63ff6c80aa7d01a693aece82395003a to your computer and use it in GitHub Desktop.
Save BoxedBrain/f63ff6c80aa7d01a693aece82395003a to your computer and use it in GitHub Desktop.
Move all open windows to the main monitor with PowerShell
# Load the necessary user32.dll functions
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class User32 {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, [MarshalAs(UnmanagedType.Bool)] bool bRepaint);
public struct RECT {
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
"@
# Get the primary monitor's dimensions
$primaryMonitor = [System.Windows.Forms.Screen]::PrimaryScreen
$primaryScreenWidth = $primaryMonitor.Bounds.Width
$primaryScreenHeight = $primaryMonitor.Bounds.Height
# Get all open windows
$windows = Get-Process | Where-Object { $_.MainWindowTitle -ne "" } | ForEach-Object { $_.MainWindowHandle }
# Iterate through each window
foreach ($window in $windows) {
# Get the current window rectangle
$rect = New-Object User32+RECT
[User32]::GetWindowRect($window, [ref]$rect) | Out-Null
# Move the window to the primary monitor
[User32]::MoveWindow($window, 0, 0, $rect.Right - $rect.Left, $rect.Bottom - $rect.Top, $true) | Out-Null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment