How To keep PowerShell VisualBasic MessageBox in Focus

 

I faced issue where I was using Visual Basic MessageBox for showing messages to users, but the popups were getting hidden behind my tool window. I had to explicitly select them, bring them to front and take action on the popup.

I also tried using ‘System.Windows.Forms.MessageBox’ but it again resulted in a popup window that was hidden behind the tool.

Solution

To keep MessageBox in Focus and on top of all windows, you can use one of the enumerator values ‘ShowModal’ for MessageBox Style.

Examples are:-

1. For Error

[Microsoft.VisualBasic.Interaction]::MsgBox("Some error occurred.", "OKOnly,SystemModal,Critical", "Error")


2. For Warning

[Microsoft.VisualBasic.Interaction]::MsgBox("Please correct fields.", "OKOnly,SystemModal,Exclamation", "Warning")

3. Success Message

[Microsoft.VisualBasic.Interaction]::MsgBox("Processing Completed.", "OKOnly,SystemModal,Information", "Success")


A full working code would look like

[void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic") 

[Microsoft.VisualBasic.Interaction]::MsgBox("Some error occurred.", "OKOnly,SystemModal,Critical", "Error")

[Microsoft.VisualBasic.Interaction]::MsgBox("Please correct fields.", "OKOnly,SystemModal,Exclamation", "Warning")

[Microsoft.VisualBasic.Interaction]::MsgBox("Processing Completed.", "OKOnly,SystemModal,Information", "Success")

There are various other combinations that are part of Message Box Style Enumerator

ApplicationModal, DefaultButton1, OkOnly, OkCancel, AbortRetryIgnore, YesNoCancel, YesNo, RetryCancel, Critical, Question, Exclamation,
Information, DefaultButton2, DefaultButton3, SystemModal, MsgBoxHelp, MsgBoxSetForeground, MsgBoxRight, MsgBoxRtlReading

Use the one which suits your need.

Conclusion

Message Box style enumerator is the key to get various styles of Message Box. ‘ShowModal’ will help you to keep focus on Message Box.

 

Happy Coding!!!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.