Powershell messagebox system windows forms

Sometimes while a powershell script is running you want to show a MessageBox with a information or warning to the user. In Windows Powershell no Commandlet exists to show a Message Box.

Nevertheless it is possible by using the .NET Windows.Forms.MessageBox class:-).

First of all load the assembly.

# Load assembly
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

To show the messagebox call the static function show(“Message Text”)

$oReturn=[System.Windows.Forms.Messagebox]::Show("This is the Message text")

The function returned a value of enum System.Windows.Forms.DialogResult, that indicates which Button was pressed.
Possible Returncodes, depending on which button was pressed, are:

[system.enum]::getValues($oReturn.GetType())
None
OK
Cancel
Abort
Retry
Ignore
Yes
No

The default Button is the OK Button, there are further 5 combinations, see below.

[system.enum]::getNames([System.Windows.Forms.MessageBoxButtons])|foreach{[console]::Writeline("{0,20} {1,-40:D}",$_,[System.Windows.Forms.MessageBoxButtons]::$_.value__)}
                  OK 0
            OKCancel 1
    AbortRetryIgnore 2
         YesNoCancel 3
               YesNo 4
         RetryCancel 5

An Example, a Message box with an Ok and a Cancel button and a check which button was pressed:

$oReturn=[System.Windows.Forms.MessageBox]::Show("Message Text","Title",[System.Windows.Forms.MessageBoxButtons]::OKCancel)	
switch ($oReturn){
	"OK" {
		write-host "You pressed OK"
		# Enter some code
	} 
	"Cancel" {
		write-host "You pressed Cancel"
		# Enter some code
	} 
}

[System.Windows.Forms.MessageBoxButtons]::OKCancel

[System.Windows.Forms.MessageBoxButtons]::OKCancel

Some examples

[System.Windows.Forms.MessageBoxButtons]::AbortRetryIgnore

[System.Windows.Forms.MessageBoxButtons]::AbortRetryIgnore
[System.Windows.Forms.MessageBoxButtons]::YesNoCancel
[System.Windows.Forms.MessageBoxButtons]::YesNoCancel

you can also use the number instead of the numeric constants to specify the buttons

[System.Windows.Forms.MessageBox]::Show("Message Text","Title",1)

This oneliner shows all possible Button combinations consecutively

[system.enum]::getValues([System.Windows.Forms.MessageBoxButtons])|foreach {[System.Windows.Forms.MessageBox]::Show("["+$_.GetType()+"]::"+$_.ToString(),"Message box Buttons",$_)}

You can style the message box with an icon, 4 are available

[system.enum]::getNames([System.Windows.Forms.MessageBoxIcon])|foreach{[console]::Writeline("{0,20} {1,-40:D}",$_,[System.Windows.Forms.MessageBoxIcon]::$_.value__)}
                None 0
                Hand 16
               Error 16
                Stop 16
            Question 32
         Exclamation 48
             Warning 48
            Asterisk 64
         Information 64

Example:

[System.Windows.Forms.MessageBox]::Show("Message Text","Title",[System.Windows.Forms.MessageBoxButtons]::OKCancel,[System.Windows.Forms.MessageBoxIcon]::Warning)

[System.Windows.Forms.MessageBoxIcon]::Warning

[System.Windows.Forms.MessageBoxIcon]::Warning

Same with numbers instead of numeric constants

[System.Windows.Forms.MessageBox]::Show("Message Text","Title",1,48)

the remaining…

[System.Windows.Forms.MessageBoxIcon]::Question

[System.Windows.Forms.MessageBoxIcon]::Question
[System.Windows.Forms.MessageBoxIcon]::Hand, Stop or Error
[System.Windows.Forms.MessageBoxIcon]::Hand, Stop or Error
[System.Windows.Forms.MessageBoxIcon]::Asterisk or Information
[System.Windows.Forms.MessageBoxIcon]::Asterisk or Information
 

All available icons consecutively

[system.enum]::getValues([System.Windows.Forms.MessageBoxIcon])|foreach {[System.Windows.Forms.Messagebox]::Show("["+$_.GetType()+"]::"+$_.ToString(),"Message box Icons",[System.Windows.Forms.MessageBoxButtons]::OK,$_)}

Michael

Advertisment to support michlstechblog.info

Я не нашел способа сделать так,  что бы вызываемое окно было поверх всех остальных окон, с помощью стандартных средств PS:

[System.Windows.Forms.MessageBox]::Show("Message","Title")

Но я знаю что в VBS есть свойство MsgBox под названием SystemModal, которое как раз и заставляет появляться popup окно поверх всех, расположенных на экране.

Мы можем убедиться в этом так:

# Добавляем в сеанс возможность использовать VBS
Add-Type -AssemblyName Microsoft.VisualBasic
# Смотрим доступные свойства
[System.Enum]::GetNames( [Microsoft.VisualBasic.MsgBoxStyle] )

Доступные свойства

Доступные свойства

Убедившись в наличии нужного свойства, мы можем использовать этот Workaround aka «костыль»:

# Выводим MsgBox поверх всех окон
[Microsoft.VisualBasic.Interaction]::MsgBox("Text", "OKOnly,SystemModal,Information", "Title")
UPD:

В итоге я разобрался, как используя Forms.MessageBox сделать окно «поверх всех».

( $FrmMain = New-Object 'System.Windows.Forms.Form' ).TopMost = $True
[System.Windows.Forms.MessageBox]::Show($FrmMain,"Текст", "Заголовок", 4, 48)

На первый взгляд этот способ ничем не лучше предыдущего, но он немного короче и не требует подгрузки дополнительных компонентов.
А так же в PowerShell версии 6.1 удален командлет Add-Type.

Хотя VisualBasic по прежнему должен  подгружаться через .NET

[System.Reflection.Assembly]::loadwithpartialname("Microsoft.VisualBasic")
 Посмотреть доступные типы форм и иконок можно следующими командами
[System.Enum]::GetNames([System.Windows.Forms.MessageBoxButtons])
[System.Enum]::GetNames([System.Windows.Forms.MessageBoxIcon])

System.Enum.MessageBox

System.Enum.MessageBox

Еще у полученных параметров есть соответствующие им числовые коды, кстати такие же как и в VBS:

# Выбор типа используемой формы
Ok = 0
OkCancel = 1
AbortRetryIgnore = 2
YesNoCancel = 3
YesNo = 4
RetryCancel= 5

# А доступные иконки с помощью
Critical = 16
Question = 32
Warning = 48
Informational = 64
Записать ответ диалогового окна в переменную

Бонусом напишу, что для получения ответа в переменную нужно просто присвоить ей команду на вызов окна:

$ans = [System.Windows.Forms.MessageBox]::Show($FrmMain,"Вы хотите открыть Блокнот?", "Подтверждение", 4, 32)
if($ans -eq "Yes"){start Notepad}

Записки администратора

User interaction is essential for building user-friendly PowerShell scripts. In this article, we explore the power of the PowerShell MessageBox functionality, enabling you to display informative messages, gather user input, and enhance the interactivity of your scripts. Join us as we uncover the potential of MessageBox in PowerShell and elevate your script’s user experience.

Making a PowerShell MessageBox with Terminal.Gui

Creating a PowerShell message box using Terminal.Gui can be done by utilizing the features provided by the library. Terminal.Gui is a text-based user interface toolkit for .NET that allows you to create console-based applications with GUI elements.

To create a message box, you can follow these steps:

  • Install the Terminal.Gui module if you haven’t already done so. You can use the following command in PowerShell to install it from the PowerShell Gallery:
Install-Module -Name Terminal.Gui
Making a PowerShell MessageBox with Terminal.Gui
  • Import the Terminal.Gui module into your PowerShell session:
Import-Module -Name Terminal.Gui
Making a PowerShell Message Box with Terminal.Gui
  • Create a function or script that displays the message box. Here’s an example:
function Show-MessageBox {
    Add-Type -AssemblyName System.Windows.Forms

    [System.Windows.Forms.MessageBox]::Show("Hello, world!", "Message Box", "OK", [System.Windows.Forms.MessageBoxIcon]::Information)
}
Making a PowerShell Message Box with Terminal.Gui
  • Call the function or script to display the message box:
Show-MessageBox
Making a PowerShell Message Box with Terminal.Gui

This will open a message box with the specified message (“Hello, world!”) and a title (“Message Box”). It will have an “OK” button and an information icon.

Note that this approach relies on the System.Windows.Forms.MessageBox class from the .NET Framework to display the message box. Terminal.Gui itself does not provide a direct message box component.

Making a PowerShell Message Box with Avalonia

Creating a PowerShell message box using Avalonia requires incorporating the Avalonia UI framework into your PowerShell script. Avalonia is a cross-platform UI framework for .NET that allows you to create rich desktop applications.

Here’s an example of how you can create a message box using Avalonia in PowerShell:

  • Install the Avalonia package if you haven’t already done so. You can use the following command in PowerShell to install it from the NuGet package manager:
Install-Package Avalonia
Making a PowerShell Message Box with Avalonia
  • Import the necessary namespaces and initialize the Avalonia application:
Add-Type -AssemblyName Avalonia
Add-Type -AssemblyName Avalonia.Controls

[Avalonia.Application]::Initialize()
Making a PowerShell Message Box with Avalonia
  • Create a function or script that displays the message box. Here’s an example:
function Show-MessageBox {
    $window = New-Object Avalonia.Controls.Window
    $window.Content = "Hello, world!"
    $window.Title = "Message Box"
    $window.Width = 300
    $window.Height = 150

    $button = New-Object Avalonia.Controls.Button
    $button.Content = "OK"
    $button.Click.Add({
        $window.Close()
    })

    $window.Content = $button

    $window.ShowDialog()
}
Making a PowerShell Message Box with Avalonia
  • Call the function or script to display the message box:

Show-MessageBox

This will create a message box with the specified message (“Hello, world!”) and a title (“Message Box”). It will have an “OK” button that closes the message box when clicked.

Note that this approach relies on creating an Avalonia window and adding UI controls to it. Avalonia allows you to build more complex UIs with various controls and layouts beyond a simple message box.

In conclusion, PowerShell’s MessageBox functionality provides a valuable tool for enhancing user interaction and improving the user experience in PowerShell scripts. By leveraging MessageBox, you can display informative messages, gather user input, and create dynamic and interactive scripts. Incorporate MessageBox into your PowerShell toolkit and take your scripts to the next level of user engagement and satisfaction.

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.)

While it is great that PowerShell can do so many things in the background without having to interact with it, occasionally it might be useful to have a graphical notification. For example, when a job finishes or when input is required in order for the script to be able to continue. For this purpose a popup window can be displayed; this is possible using the Windows.Forms namespace and in particular the MessageBox class.

The following example will display a MessageBox form with an OK button and the ‘Hello World’ text:

1
2
Add-Type -AssemblyName System.Windows.Forms | Out-Null
[System.Windows.Forms.MessageBox]::Show("Hello World")

The MessageBox class can accept more arguments than just a single string. To explore the possible constructors the Show method can be called without any parameters displaying all OverloadDefinitions. In the following code the OverloadDefinitions and the total count of possible definitions will be displayed:

1
2
[System.Windows.Forms.MessageBox]::Show
[System.Windows.Forms.MessageBox]::Show.OverloadDefinitions.Count

The output from the previous command shows that it is possible to change the MessageBoxButtons and that it is possible to add a MessageBoxIcon. The GetNames method of the Enum class can be called to enumerate the possible entries for these options:

1
2
[Enum]::GetNames([System.Windows.Forms.MessageBoxButtons])
[Enum]::GetNames([System.Windows.Forms.MessageBoxIcon])

The parameters for Title, Caption, MessageBoxButtons and MessageBoxIcon will be specified to create a new MessageBox. The output will be stored in the $MessageBox variable and can be used for further execution in the script:

1
2
3
$MessageBox = [System.Windows.Forms.MessageBox]::Show(
    'Text','Caption','YesNoCancel','Question'
)

For more information about the MessageBox class and to view all the definitions have a look at its MSDN entry:

MessageBox Class

Share on:

  • Powerpoint 2016 скачать бесплатно для windows 10 торрент
  • Powerpoint 2016 скачать бесплатно для windows 10 без ключа
  • Postgresql скачать для windows 10 64 bit
  • Postgresql скачать бесплатно для windows 10
  • Postgresql пользователь не прошел проверку подлинности по паролю windows