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 } }
Some examples
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)
Same with numbers instead of numeric constants
[System.Windows.Forms.MessageBox]::Show("Message Text","Title",1,48)
the remaining…
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
- Details
- Written by June Blender
- Last Updated: 23 December 2016
- Created: 15 December 2016
- Hits: 61568
MessageBox Control [System.Windows.Forms.MessageBox]
Displays a modal window with a message for the user and at least one button. The MessageBox closes only when the user clicks a MessageBox button. A MessageBox can contain text, buttons, and symbols that show information to the user and require their response.
MSDN Page: System.Windows.Forms.MessageBox
A modal window is a child of the parent form that opens on top of it. When a modal window opens, the parent form is temporarily disabled, but still visible. When the user clicks a modal window button, the modal window closes and control passes back to the parent window, which is re-enabled.
Message boxes are typically used to display important information that the user must acknowledge, such as error messages. Using a MessageBox to display user messages, instead of a custom form, helps to standardize your application and assure that it conforms to best practice design standards.
There is a WinForms MessageBox class (System.Windows.Forms.MessageBox), but there is no MessageBox control in PowerShell Studio Toolbox pane.
In this article
- Create a MessageBox
- Tips for using a MessageBox
- MessageBox Variations
Create a MessageBox
To create a MessageBox:
Use the Show static method of the MessageBox class.
[System.Windows.Forms.MessageBox]::Show('text', 'title')
For example:
[System.Windows.Forms.MessageBox]::Show("Cannot find drivers on computer: $ComputerName", 'Driver fetch error')
Generates this message box when the value of $ComputerName is ‘SAPIEN-007’.
To create a MessageBox in PowerShell Studio:
- Use the msgbox or msgboxyesno snippets
- Replace the ‘Text’ placeholder with the text that appears in the message box.
- Replace the ‘Title’ placeholder with the window title.
Here is the MessageBox that the msgbox snippet creates before the ‘Text’ and ‘Title’ placeholders are replaced.
Because the MessageBox class does not have constructors (special methods for creating an object of that class), you do not use the New-Object cmdlet or the New static method to create a MessageBox. Use the Show static method instead.
The Show method has 21 different overloads (like parameter sets) and you can use any overload to create your MessageBox.
Tips for using a MessageBox Control
- Unlike other controls in a PowerShell GUI application, you do not create a MessageBox in advance and write event handlers for it. Instead, you create it in the code where you use it.
- In PowerShell Studio, to add the code for a MessageBox, use the msgbox or msgboxyesno snippet. These snippets create a simple MessageBox with a window title, a message, an OK button and the system close button (X) in the upper right corner. For a more complex MessageBox, see MessageBox Variations.
- The first line of the msgbox and msgboxyesno snippets is an Add-Type command that adds the System.Windows.Forms assembly to the session. In PowerShell Studio, you need this command only when displaying a MessageBox in a .ps1 file. In a .psf file, you can comment-out this line or delete it.
#Add-Type -AssemblyName «System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089»
- The msgbox and msgboxyesno snippets come with single-quoted strings. If your message strings include variables, be sure to change to double-quoted strings. For more information, see about_Quoting_Rules.
[void][System.Windows.Forms.MessageBox]::Show('Text', 'Title') [void][System.Windows.Forms.MessageBox]::Show("Cannot find computer: $ComputerName", 'Computer name error')
- The Show method parameter values must be strings (enclosed in quotations marks), integers that represent an enumeration value, or variables.
- When the user closes the MessageBox, the Show method returns a DialogResult value that represents the button that the user clicked to close the MessageBox, such as ‘OK’. To suppress the output, pipe it to Out-Null, assign it to $null, or cast it as [void]. For example:
$null = [System.Windows.Forms.MessageBox]::Show("Cannot find drivers on computer: $ComputerName", 'Driver fetch error')
- If you’re using a more complex variation of the Show method, but can’t remember the parameters or parameter order, PowerShell Studio will prompt you.
Type:
[System.Windows.Forms.MessageBox]::Show(PowerShell Studio prompts with the parameters for different overloads of the Show method. To scroll through the options, use the up-arrow and down-arrow keys. To select an overload, press TAB. PowerShell Studio adds the parameters for you.
- You can display a MessageBox in your Form_Load event handler. For example, this code checks for a module and, if it’s not installed, it displays a MessageBox and then closes the form. This is handy because #Requires -Module generates a console error and prevents the script from running, but it does not display anything to the GUI app user.
$formShow_Load = { if (!(Get-Module -Name CoolNewThing -ListAvailable)) { $msg = "This app requires the CoolNewThing module. Install the module and try again.`n`nClosing this app." [System.Windows.Forms.MessageBox]::Show($msg, 'Required module not found', 'OK', 'Error') $formShow.Close() } }
- You can also add a MessageBox to a console command or a script (.ps1). Be sure to include the Add-Type command that adds the System.Windows.Forms assembly to the session. You can find the Add-Type command in the msgbox and msgboxyesno snippets.
MessageBox Variations
The Show method of the MessageBox class has many variations or overloads, which are like Windows PowerShell parameter sets. This section lists and explains some of the most frequently used overloads of the Show method of MessageBox class .
- Message only
- Message and Title
- Message, Title, and Buttons
- Add Icon
- Set the Default Button
- Add MessageBox Options
- Add a Help Button
Message only
MSDN: https://msdn.microsoft.com/en-us/library/519bytz3(v=vs.110).aspx
[System.Windows.Forms.MessageBox]::Show('text')
To create a MessageBox with text, but no title, enter a single string. To break a line or create paragraphs in the string, use the newline character, `n (backtick-n).
[System.Windows.Forms.MessageBox]::("Cannot find drivers on computer: $Computer")
Message and Title
MSDN: https://msdn.microsoft.com/en-us/library/20stz12s(v=vs.110).aspx
[System.Windows.Forms.MessageBox]::Show('text', 'title')
To create a Message box with text and title, call the Show method with two strings. The first string is the MessageBox text; the second string is the window title.
[System.Windows.Forms.MessageBox]::("Cannot find drivers on computer: $Computer", 'Driver fetch error')
Message, Title, and Buttons
MSDN: https://msdn.microsoft.com/en-us/library/0x49kd7z(v=vs.110).aspx
[MessageBox]::Show(‘text’, ‘title’, MessageBoxButtons)
NOTE: When you specify MessageBoxButtons values other than ‘Ok’ that do not include a Cancel button, the system close button (X) in the upper right corner of the MessageBox is disabled.
[System.Windows.Forms.MessageBox]::Show('text', 'title', MessageBoxButtons)
To create a Message box with text and title and specified buttons (up to 3 buttons), call the Show method with two strings, and a MessageBoxButtons option, such as OK, YesNo, or YesNoCancel. By default, a MessageBox has an OK button. You can replace the OK button, but you cannot remove all buttons. To add a Help button, use a HelpButton overload.
$result = [System.Windows.Forms.MessageBox]::("Cannot find drivers on computer: $Computer", 'Driver fetch error', 'OKCancel')
When using multiple buttons, use the DialogResult value that the Show method returns to respond to the user’s button choice. For example:
$buttonStart={ Try {Get-Service -ComputerName $textboxCn.Text.Trim() | Out-GridView} Catch { $result = [System.Windows.Forms.MessageBox]::Show('Failed. Get services on local computer?', 'Computer name error', 'YesNo') if ($result -eq 'Yes') { Get-Service | Out-GridView } } }
Notice that when you specify MessageBoxButtons that do not include a Cancel button, the system close button (X) in the upper right corner of the MessageBox is disabled. The exception is ‘OK’, which is the default value.
Add Icon
MSDN: https://msdn.microsoft.com/en-us/library/365dky5y(v=vs.110).aspx
[MessageBox]::Show(‘text’, ‘title’, MessageBoxButtons, MessageBoxIcon)
[System.Windows.Forms.MessageBox]::Show('text', 'title', MessageBoxButtons, MessageBoxIcon)
This Show method overload adds a MessageBoxIcon option, such as Exclamation, Warning, or Stop. The icon that appears varies with the version of Windows on the local system.
For example:
$result = [System.Windows.Forms.MessageBox]::("Cannot find drivers on computer: $Computer", 'Driver fetch error', 'OKCancel', 'Error')
This Show method requires a MessageBoxButtons value. You cannot skip the parameter or insert an empty string. To omit the icon, use a value of ‘None’.
Set the Default Button
MSDN: https://msdn.microsoft.com/en-us/library/ctd56yay(v=vs.110).aspx
[MessageBox]::Show(‘text’, ‘title’, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton)
[System.Windows.Forms.MessageBox]::Show('text', 'title', MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton)
This Show method overload adds a MessageBoxDefaultButton option, Button1, Button2, or Button3. The ButtonX values refer to left-to-right order of the buttons. Button1 is the default. When a button is the default, that button is highlighted and is clicked when the user presses the Enter key.
For example:
$result = [System.Windows.Forms.MessageBox]::("Cannot find drivers on computer: $Computer. Run on local computer?", 'Driver fetch error', 'YesNoCancel', 'Error', 'Button2')
Add MessageBox Options
[MessageBox]::Show(‘text’, ‘title’, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions)
MSDN: https://msdn.microsoft.com/en-us/library/ba3x8zfh(v=vs.110).aspx
[System.Windows.Forms.MessageBox]::Show('text', 'title', MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions)
This Show method overload adds a MessageBoxOptions value. The RightAlign and RtlReading attributes are designed for aligning text near buttons and for right-to-left languages. The DefaultDesktopOnly and ServiceNotification values keep the MessageBox on top of other windows, which might be useful for very high priority messages in multi-window applications. You can also enter a value of 0, which satisfies the MessageBoxOption value requirement without selecting any of the options.
For example:
$result = [System.Windows.Forms.MessageBox]::("Cannot find drivers on computer: $Computer. Run on local computer?", 'Driver fetch error', 'YesNoCancel', 'Error', 'Button2', RightAlign)
Also, the MessageBoxOptions enumeration has a FlagsAtttribute that lets you select multiple enum values, rather than choosing just one.
$MBOptions = [System.Windows.Forms.MessageBoxOptions]"RightAlign, DefaultDesktopOnly" [System.Windows.Forms.MessageBox]::Show("Cannot find drivers on computer: SAPIEN-007.", 'Driver fetch error', 'OK', 'Error', 'Button2', $MBOptions
Add a Help Button to a MessageBox
There are several Show overloads that create a Help button in a MessageBox.
IMPORTANT:
- You cannot use a MessageBoxOptions value of DefaultDesktopOnly or ServiceNotification with a help button in a message box.
- When the user clicks the Help button in the MessageBox, the form receives the HelpRequested event. To respond to this event, add a HelpRequested event handler to the form.
Use this syntax to add a Help button that displays the text in a file or opens a web page. This Show overload does not work properly in the Form_Load event handler.
MSDN: https://msdn.microsoft.com/en-us/library/tewzaxwc(v=vs.110).aspx
[MessageBox]::Show(‘text’, ‘title’, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, HelpPathString)
[System.Windows.Forms.MessageBoxMessageBox]::Show('text', 'title', MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, HelpPathString)
Use this syntax to add a Help button with a custom response, such as launching a child form or starting a wizard.
MSDN: https://msdn.microsoft.com/en-us/library/szwxe9we(v=vs.110).aspx
[MessageBox]::Show(‘text’, ‘title’, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, Boolean)
[System.Windows.Forms.MessageBoxMessageBox]::Show('text', 'title', MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, Boolean)
Display Help from a File or Web Page
To add a MessageBox Help button that displays the text from a text file or opens a web page, add the text file path to the Show method arguments.
For example, this script displays a MessageBox with a Help button that opens a Windows PowerShell About help file on disk.
$msg = 'Cannot interpret symbols or special characters in input string.' $HelpFilePath = "$PSHOME\en-US\about_Special_Characters.help.txt" [System.Windows.Forms.MessageBox]::Show($msg, 'Invalid input', 'OK', 'Stop', 'Button3', 0, $HelpFilePath)
The obvious risk of this strategy is that the file isn’t found. Before using this method use the Test-Path cmdlet to verify the file location and provide an alternative or use this method only with files installed with your application.
You can also use a URL in the HelpFilePath string value.
$msg = 'Cannot interpret symbols or special characters in input string.' $HelpFilePath = 'http://go.microsoft.com/fwlink/?LinkID=113269'
[System.Windows.Forms.MessageBox]::Show($msg, 'Invalid input', 'OK', 'Stop', 'Button3', 0, $HelpFilePath)
Display Help in Other Ways
You can add a Help button to a MessageBox and then write an event handler to respond to clicking the Help button. This lets you respond to the Help button click in a variety of ways, such as by displaying a Help window child form or opening a web page.
This Show method overload adds a Boolean value. Enter $True to add a Help Button; $False to omit the Help button.
Remember to set the MessageBoxOptions to 0 or to a value other than DefaultDesktopOnly or ServiceNotification. To make the Help button the default, set the value of MessageBoxDefaultButton to the last button. In this case, with OK, Cancel, and Help buttons, Help is Button3.
[System.Windows.Forms.MessageBox]::("Cannot find drivers on computer: $Computer. Run on local computer?", 'Driver fetch error', 'OKCancel', 'Error', 'Button3', 0, $True)
When the user clicks the Help button on the MessageBox, it raises the HelpRequested event on the parent form (not on the MessageBox). To respond to the Help button click event, add an event handler for the HelpRequested event to the parent form.
Add a HelpRequested event handler
When the user clicks the Help button on the MessageBox, it raises the HelpRequested event on the parent form (not on the MessageBox). To respond to the Help button click event, add an event handler for the HelpRequested event to the parent form.
To add the HelpRequested event handler:
- Click the Designer tab and, in the Properties pane for the form, click the Event button (lightening icon).
- Double-click the HelpRequested event.
PowerShell Studio adds an event handler for the HelpRequested event (of the form) to your script.
This sample event handler opens a web page, but you can respond to the Help button click in many different ways.
For more information:
- VIDEO! MessageBox: Display user messages in a PowerShell GUI app
- Manage Errors in a GUI Application
- Displaying Output in a GUI Application
- Spotlight articles? In PowerShell Studio, in the Toolbox or in the Properties pane, right-click a control and then click View Spotlight Article.
Последнее обновление: 31.10.2015
Как правило, для вывода сообщений применяется элемент MessageBox. Однако кроме сообственно вывода строки сообщения данный элемент может устанавливать
ряд настроек, которые определяют его поведение.
Для вывода сообщения в классе MessageBox предусмотрен метод Show, который имеет различные версии и может принимать ряд параметров.
Рассмотрим одну из наиболее используемых версий:
public static DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options )
Здесь применяются следующие параметры:
text
: текст сообщения
caption
: текст заголовка окна сообщения
buttons
: кнопки, используемые в окне сообщения.
Принимает одно из значений перечисления MessageBoxButtons:
-
AbortRetryIgnore
: три кнопки Abort (Отмена), Retry (Повтор), Ignore (Пропустить) -
OK
: одна кнопка OK -
OKCancel
: две кнопки OK и Cancel (Отмена) -
RetryCancel
: две кнопки Retry (Повтор) и Cancel (Отмена) -
YesNo
: две кнопки Yes и No -
YesNoCancel
: три кнопки Yes, No и Cancel (Отмена)
Таким образом, в зависимости от выбора окно сообщения может иметь от одной до трех кнопок.
icon
: значок окна сообщения. Может принимать одно из следующих значений перечисления MessageBoxIcon:
-
Asterisk, Information
: значок, состоящий из буквы i в нижнем регистре, помещенной в кружок -
Error, Hand, Stop
: значок, состоящий из белого знака «X» на круге красного цвета. -
Exclamation, Warning
: значок, состоящий из восклицательного знака в желтом треугольнике -
Question
: значок, состоящий из вопросительного знака на периметре круга -
None
: значок у сообщения отсутствует
defaultButton
: кнопка, на которую по умолчанию устанавливается фокус. Принимает одно из значений перечисления MessageBoxDefaultButton:
-
Button1
: первая кнопка из тех, которые задаются перечислением MessageBoxButtons -
Button2
: вторая кнопка -
Button3
: третья кнопка
options
: параметры окна сообщения. Принимает одно из значений перечисления MessageBoxOptions:
-
DefaultDesktopOnly
: окно сообщения отображается на активном рабочем столе. -
RightAlign
: текст окна сообщения выравнивается по правому краю -
RtlReading
: все элементы окна располагаются в обратном порядке справа налево -
ServiceNotification
: окно сообщения отображается на активном рабочем столе, даже если в системе не зарегистрирован ни один пользователь
Нередко используется один параметр — текст сообщения. Но посмотрим, как использовать остальные параметры. Пусть у нас есть кнопка, в обработчике
нажатия которой открывается следующее окно сообщения:
private void button1_Click(object sender, EventArgs e) { MessageBox.Show( "Выберите один из вариантов", "Сообщение", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); }
Однако нам не просто дается возможность установки кнопок в окне сообщения. Метод MessageBox.Show
возвращает объект
DialogResult, с помощью которого мы можем узнать, какую кнопку в окне сообщения нажал пользователь. DialogResult представляет
перечисление, в котором определены следующие значения:
-
Abort
: нажата кнопка Abort -
Retry
: нажата кнопка Retry -
Ignore
: нажата кнопка Ignore -
OK
: нажата кнопка OK -
Cancel
: нажата кнопка Cancel -
None
: отсутствие результата -
Yes
: нажата кнопка Yes и No -
No
: нажата кнопка No
Используем обработку выбора пользователя, изменив обработчик нажатия кнопки следующим образом:
private void button1_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show( "Окрасить кнопку в красный цвет?", "Сообщение", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); if (result == DialogResult.Yes) button1.BackColor=Color.Red; this.TopMost = true; }
И теперь, если в окне сообщения мы выберем выриант Yes, то кнопка окрасится в красный цвет.
Я не нашел способа сделать так, что бы вызываемое окно было поверх всех остальных окон, с помощью стандартных средств 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])
Еще у полученных параметров есть соответствующие им числовые коды, кстати такие же как и в 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}
Записки администратора
Complete program. The MessageBox.Show method is a static method. This means you do not need to create a new MessageBox() anywhere in your code.
Instead: You can simply type «MessageBox» and press the period, and then select Show.
Here: In this example, the MessageBox.Show method is used in the Form1_Load event handler.
Tip: To make the Form1_Load event handler, create a new Windows Forms application and double-click on the window in the designer.
C# program that uses MessageBox
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//
// The simplest overload of MessageBox.Show.
//
MessageBox.Show
(«The Dev Codes is awesome.»);
//
// Dialog box with text and a title.
//
MessageBox.Show
(«The Dev Codes is awesome.»,
«Important Message»);
//
// Dialog box with two buttons: yes and no.
//
DialogResult result1 =
MessageBox.Show
(«Is The Dev Codes awesome?»,
«Important Question»,
MessageBoxButtons.YesNo);
//
// Dialog box with question icon.
//
DialogResult result2 =
MessageBox.Show
(«Is The Dev Codes awesome?»,
«Important Query»,
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
//
// Dialog box with question icon and default button.
//
DialogResult result3 =
MessageBox.Show
(«Is Visual Basic awesome?»,
«The Question»,
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
//
// Test the results of the previous three dialogs.
//
if (result1 == DialogResult.Yes &&
result2 == DialogResult.Yes &&
result3 == DialogResult.No)
{
MessageBox.Show
(«You answered yes, yes and no.»);
}
//
// Dialog box that is right-aligned (not useful).
//
MessageBox.Show
(«The Dev Codes is the best.»,
«Critical Warning»,
MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign,
true);
//
// Dialog box with exclamation icon.
//
MessageBox.Show
(«The Dev Codes is super.»,
«Important Note»,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
}
}