Question:
So while there is much advise about how to set forms topmost, i couldnt find anything that makes my console run topmost.
So my question: How do I make my console run top-most during a script?
Answer:
This requires some .NET interop, as detailed in this blog:
Scripts From TechEd 2012… Part 1 (Keeping PowerShell Window On Top)
I’ve copied the relevant code below in case the linked site disappears:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$signature = @' [DllImport("user32.dll")] public static extern bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); '@ $type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru $handle = (Get-Process -id $Global:PID).MainWindowHandle $alwaysOnTop = New-Object -TypeName System.IntPtr -ArgumentList (-1) $type::SetWindowPos($handle, $alwaysOnTop, 0, 0, 0, 0, 0x0003) |
Edit:
As described in the comments: If you’re from a batch file, PowerShell runs in a child process and doesn’t own the console window, so you’ll have to make changes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$signature = @' [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] public static extern bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); '@ $type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru $handle = $type::GetConsoleWindow() $type::SetWindowPos($handle, -1, 0, 0, 0, 0, 0x0003) |