MessageBox - looking for a better way

This is what I am currently doing to set the default button on a message box:

Add-Type -AssemblyName System.Windows.Forms
$msgBox = [Windows.Forms.MessageBox]
$buttonYes = [System.Windows.Forms.MessageboxDefaultButton]::Button1
$buttonNo = [System.Windows.Forms.MessageboxDefaultButton]::Button2
$buttonCancel = [System.Windows.Forms.MessageboxDefaultButton]::Button3

$msgBox::Show("Message To User.", 'Hello World', 'YesNo', 'Warning', $buttonNo)

There must be a better way. What I am hoping for is a way to simply reference the button by its position as in 1, 2, 3 etc, not having to hard code the button variable to a specific button in the enum. This method just seems quirky to me.

Any help is appreciated in advance. Thank you.

This can go all kinds of different directions. I would do this. Call the method when you need it. You can add arguments if you wish. I am keeping this super simple…

# Popup a window with a good message
Function Set-CompletePopup( )
    {
        [System.Windows.MessageBox]::Show("Something Completed", "Good to go", "OK", "Asterisk")
    }

Thanks Robert for the reply. I did not make myself clear enough. Sorry about that. I am looking for a better way to set the default button on the Message Box popup which would be the 5th argument to the Show Method. I am trying to avoid setting the variables to the Enum and for a better way to set those in the Show method. Make sense?

You can use the Button reference rather than your variable.

I took the liberty of declaring it as ‘YesNoCancel’ as I think that was your intention?

Add-Type -AssemblyName System.Windows.Forms
$msgBox = [Windows.Forms.MessageBox]
$buttonYes = [System.Windows.Forms.MessageboxDefaultButton]::Button1
$buttonNo = [System.Windows.Forms.MessageboxDefaultButton]::Button2
$buttonCancel = [System.Windows.Forms.MessageboxDefaultButton]::Button3

$msgBox::Show("Message To User.", 'Hello World', 'YesNoCancel', 'Warning', 'Button2')

Wow, thanks Matt. I am pretty sure I tried everything BUT your suggestion. Feeling pretty stupid at this point. I do believe I tried this, but without the single quotes. My bad.

1 Like