MessageBox in Powershell not brought to front

11,979

Solution 1

Spawned windows need a parent. If they don't they will fall behind other windows (as you've found).

The following isn't PowerShell related, per se ... but it's what you need to know/do to get where you want to go...

Why isn't MessageBox TopMost?

and possibly

In Powershell how do I bring a messagebox to the foreground, and change focus to a button in the message box

Solution 2

The $this method does NOT work. I do not know where you people get your information or if you even know how to code in Powershell at all, but your are providing misinformation. I tested the $this method and I can absolutely assure you that it does not work in any way shape or form in PowerShell.

Here is the only method that TRULY works in PowerShell:

Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.Interaction]::MsgBox('MyMessage','OKOnly,SystemModal,Information', 'HeaderText')

It is the SystemModal parameter that forces the MsgBox to dominate and always remains on top no matter what.

There is also another documented method, the Wscript.Shell method, that other people claim that it works, see below.

New-Object -ComObject Wscript.Shell

$wshell.Popup("MyMessage",0,"MyHeader",0 + 16 + 4096)

Where first 0 = No timeout, second 0 = OKOnly, 16 = Critical, 4096 = SystemModal

It also do NOT work as I was STILL able to go back to my previous form and make changes to it while the MsgBox was displayed, which is what I do not want.

Solution 3

You don't need to use a [System.Windows.Forms.Form] object, you can do it in 1 line by using the $this variable as the first parameter:

$Result = [System.Windows.Forms.MessageBox]::Show($this, $MessageBody, $MessageTitle, $ButtonType, $MessageIcon)
Share:
11,979
Phil O'kelly
Author by

Phil O'kelly

Updated on July 24, 2022

Comments

  • Phil O'kelly
    Phil O'kelly almost 2 years

    I'm using an application which allows me to run Powershell scripts on devices within my network and I need to prompt users with a MessageBox.

    My script creates the MessageBox fine, but my issue is that it always displays behind my application. I tried a solution online which suggested creating a new form with property Topmost=true and passing it as the first parameter, however it didn't seem to work. Is there anything immediately obvious that I'm doing wrong?

    Add-Type -AssemblyName PresentationCore,PresentationFramework
    
    $top = new-Object System.Windows.Forms.Form -property @{Topmost=$true}
    $Result = [System.Windows.Forms.MessageBox]::Show($top, $MessageBody,$MessageTitle,$ButtonType,$MessageIcon)