Problem scenario:
You have a PowerShell script that launches a pop-up window. This pop-up appears behind the PowerShell ISE GUI. Without being in the foreground, the users of this script fail to realize there is a prompt waiting for the user to take action. You want the pop-up window to be in the front. You tried things like these options to no avail:
- New-Object System.Windows.Forms.Form -Property @{TopMost = $true}
- -ArgumentList([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
- form.TopMost = "True"
- form.TopMost = $true
- form.TopMost = $True
- $form.TopLevel = $true
- set-foregroundWindow(Get-Process PowerShell).Main.WindowHandle
- $form.BringToFront()
- set-WindowsFocus
- [void]$showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 2) #hide GUI
[void]$showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 10) # GUI returns
You could use a form (not a PowerShell Window) with PowerShell code and no special Vexasoft solution, and the above may be unsuccessful in reliably (or ever) making the pop-up window appear in front of the PowerShell ISE application. Users waste time not knowing that the program is waiting on them.
The last bullet's two lines of PowerShell code were taken from this external link. In some instances, the above options will not work reliably. When the PowerShell window is not minimized there may also be an error about calling a method on a null-valued expression. When a pop-up is hidden behind the PowerShell window, the interactive experience is delayed unnecessarily.
What should you do so the pop-up GUI is clearly visible (as interactive scripts can stall until options are selected or input is provided)?
Solution
Minimize the PowerShell ISE application via the follow PowerShell code (where "start-sleep 5" is the line that launches the pop-up):
$shell = New-Object -ComObject "Shell.Application"
$shell.minimizeall()
start-sleep 5 # This is where the pop-up would be called. It is just a placeholder.
$shell = New-Object -ComObject "Shell.Application"
$shell.undominimizeall()
Every line but the middle line in the above five lines of code were taken from this external website.
Very useful, thank you for sharing!