Skip to content

Instantly share code, notes, and snippets.

@chadbaldwin
Last active September 1, 2023 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadbaldwin/843b21b510b16495b155b04882992841 to your computer and use it in GitHub Desktop.
Save chadbaldwin/843b21b510b16495b155b04882992841 to your computer and use it in GitHub Desktop.
Function to set the foreground window in Windows using the user32.dll API
function Set-ForegroundWindow {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)][string]$ProcessName
)
$type = '
using System;
using System.Runtime.InteropServices;
public class WinAp {
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}'
Add-Type $type
# Pick the first window that matches this process
$h = (Get-Process -Name $ProcessName | ? MainWindowTitle | select -First 1).MainWindowHandle
# If you can't find the window, exit
if ($null -eq $h) { return }
# https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
# 2 = Minimize window
[WinAp]::ShowWindow($h, 2) # minimize it first...this is a hack so that we maintain snapped window positions
# 4 or 9 = Restore window, these are the only ones that seem to work predictably.
# They will restore a window to its original position if it is minimized, even if the window was snapped
# However, if the window is not minimized but is only out of focus, then it will unsnap the window.
# This is why we first minimize it, then restore it. It's hacky, but it works. It just looks a little funny.
[WinAp]::ShowWindow($h, 4)
# Bring window into focus
[WinAp]::SetForegroundWindow($h)
}
# Credit to this SO Answer:
# https://stackoverflow.com/a/42567337/3474677
@chadbaldwin
Copy link
Author

[reserving first comment]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment