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!!!


Comments (2)

  1. Fascinating says:

    An fascinating dialogue is worth comment. I think that you must write more on this topic, it may not be a taboo subject however typically people are not sufficient to talk on such topics. To the next. Cheers
    voyance gratuitement – http://www.voyance-gratuitement.fr

  2. Thanks for the information. It helps in the case that when I wan the script really have attention from users.

Skip to main content