Skip to content

Instantly share code, notes, and snippets.

@Nora-Ballard
Last active May 28, 2024 08:20
Show Gist options
  • Save Nora-Ballard/11240204 to your computer and use it in GitHub Desktop.
Save Nora-Ballard/11240204 to your computer and use it in GitHub Desktop.
Hide, Show, Minimize, Maximize, etc window from Powershell.
function Set-WindowState {
param(
[Parameter()]
[ValidateSet('FORCEMINIMIZE', 'HIDE', 'MAXIMIZE', 'MINIMIZE', 'RESTORE',
'SHOW', 'SHOWDEFAULT', 'SHOWMAXIMIZED', 'SHOWMINIMIZED',
'SHOWMINNOACTIVE', 'SHOWNA', 'SHOWNOACTIVATE', 'SHOWNORMAL')]
[Alias('Style')]
[String] $State = 'SHOW',
[Parameter(ValueFromPipelineByPropertyname='True')]
[System.IntPtr] $MainWindowHandle = (Get-Process –id $pid).MainWindowHandle,
[Parameter()]
[switch] $PassThru
)
BEGIN
{
$WindowStates = @{
'FORCEMINIMIZE' = 11
'HIDE' = 0
'MAXIMIZE' = 3
'MINIMIZE' = 6
'RESTORE' = 9
'SHOW' = 5
'SHOWDEFAULT' = 10
'SHOWMAXIMIZED' = 3
'SHOWMINIMIZED' = 2
'SHOWMINNOACTIVE' = 7
'SHOWNA' = 8
'SHOWNOACTIVATE' = 4
'SHOWNORMAL' = 1
}
$Win32ShowWindowAsync = Add-Type –memberDefinition @”
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
“@ -name “Win32ShowWindowAsync” -namespace Win32Functions –passThru
}
PROCESS
{
$Win32ShowWindowAsync::ShowWindowAsync($MainWindowHandle, $WindowStates[$State]) | Out-Null
Write-Verbose ("Set Window State on '{0}' to '{1}' " -f $MainWindowHandle, $State)
if ($PassThru)
{
Write-Output $MainWindowHandle
}
}
END
{
}
}
Set-Alias -Name 'Set-WindowStyle' -Value 'Set-WindowState'
@antatec
Copy link

antatec commented May 22, 2024

Hi! Thank you very much Nora-Ballard for this code.

I've found once window has MainWindowHandle = 0, you cannot handle it or bring it back. In example: "SystemSettings" process startis with MainWindowHandle = 0 and does not respond to MINIMIZE. Same, if you send a HIDE handle to a process, you cannot get it back even when the process is there.

Haven't found a way to sort this. Thanks.

@lalibi
Copy link

lalibi commented May 24, 2024

Hi! Thank you very much Nora-Ballard for this code.

I've found once window has MainWindowHandle = 0, you cannot handle it or bring it back. In example: "SystemSettings" process startis with MainWindowHandle = 0 and does not respond to MINIMIZE. Same, if you send a HIDE handle to a process, you cannot get it back even when the process is there.

Haven't found a way to sort this. Thanks.

You can check my fork. I store the MainWindowHandles in a .json file in "$env:APPDATA\WindowHandles.json" and restore them every time the script is run. These entries are cleared after a threshold (default = 24h).

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