Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MessageBox in Powershell not brought to front

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)
like image 507
Phil O'kelly Avatar asked Dec 06 '25 06:12

Phil O'kelly


2 Answers

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.

like image 101
thedoctrine101 Avatar answered Dec 07 '25 21:12

thedoctrine101


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

like image 43
curveto Avatar answered Dec 07 '25 19:12

curveto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!