Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Messagebox.Show() from PowerShell with more than default button?

I am trying to show a message box from PowerShell with yes and no buttons.

I can display a message box with an OK button:

[system.windows.forms.messagebox]::show("Hello, world!")

And I can create a variable $buttons with the buttons I want:

$buttons=[system.windows.forms.messageboxbuttons].yesno

And I can see that the Show() static method is overloaded and that one of the options is to give three parameters:

Show(String, String, MessageBoxButtons) Displays a message box with specified text, caption, and buttons.

So naturally(?) I decided to call this:

[system.windows.forms.messagebox]::show("Are you sure?","",$buttons)

And this results in an error:

Cannot find an overload for "Show" and the argument count: "3".

But there IS an overload for "Show" that accepts three arguments!

What am I doing wrong?

(And can someone tell me why calling a method in PowerShell is usually done by using the dot syntax: object.method() but requires "::" for the MessageBox class? It's confusing.)

like image 323
Andrew J. Brehm Avatar asked Dec 29 '22 05:12

Andrew J. Brehm


2 Answers

Correct way of doing this can be

$buttons=[system.windows.forms.messageboxbuttons]::yesno;
[system.windows.forms.messagebox]::Show("Are you sure?","",$buttons);

Notice "::" instead of "." in the first line. YesNo value is defined staticly on System.Windows.Forms.Messageboxbuttons, so you must use "::" (static call) instead of "."

Note that "[system.windows.forms.messageboxbuttons].yesno" is an attempt to call a "YesNo" property on an instance of System.Type, which does not exist and therefore result in a $null

Hope it helps !

Cédric

Edit ---

Keith solution using an implicit cast made by powershell for the enum is more elegant. It just does not work on PS V2 CTP 3 which I still use but work fine on RTM version. The complete explication was worth giving, though...

like image 198
Cédric Rup Avatar answered Apr 26 '23 14:04

Cédric Rup


Try this way:

[windows.forms.messagebox]::show('body','title','YesNo')

And the distinction between using :: and . is static method vs instance method. Notice above that we didn't create a MessageBox object. We are just using a static method on MessageBox with the :: syntax.

like image 22
Keith Hill Avatar answered Apr 26 '23 13:04

Keith Hill