Msgbox Title Example For Essay

Best Excel VBA MsgBox Examples to display Message Box using VBA with Options and Types. Message Box (msgbox) VBA Macros explained with syntax. Use MsgBox in VBA to show vbYes, No and Cancel, vbexclamation, vbcritical, vbinformation message boxes and other advanced popup messages box models to display with icons and command buttons.

VBA MsgBox Function

VBA MsgBox is one of the most frequently used functions in VBA Application Development. We can use MsgBox Function in Microsoft Word, Excel, Access and PowerPoint VBA Programming. Excel VBA Message Box function displays a message, optional icon and selected set of command buttons in a dialog box. It waits for the user to click a button, and returns an Integer indicating the button which user clicked. Here is the syntax and different kinds of Message Boxes in VBA.

VBA MsgBox – Syntax:

Here is the syntax of VBA MsgBox Function. This is same in Excel, Word, Access, PowerPoint and VBScript.

MsgBox(prompt

[, buttons] [, title] [, helpfile, context])

Where

  1. Prompt: It Contains String expression displayed as the message in the dialog box. The Maximum length of Prompt is 1024 Characters. You can use carriage return Character,If prompt consists more than one line.
  2. buttons:It Contains Numeric value specifying the number and type of buttons to display.The default button value is 0.
  3. title:It Contains String expression displayed in the title bar of the dialog box.

Here is a short video to show you VBA Message Box with different types of options:

Here are the different types of Message Boxes available in Excel VBA. You can click on each link to see the respective examples, Screenshots of output and explanation.

VBA MsgBox arguments

VBA MsgBox will take the following parameters: These options will change the appearance of the Message Box. You can change the model of the Message Box by combining different option of MsgBox Function.

  • MsgBox Prompt: This is the message text which you want to show/prompt
  • MsgBox Buttons Style: This is the type of message box which you want to show, like Yes No buttons with Information Icon
  • MsgBox Title: This is the title of the message box window
  • MsgBox Help File, and Context: These are the other optional parameters which we use in very rare

Here is the Hello World MsgBox Function example with Parameters.

MsgBox “Hello World!”, vbYesNo + vbInformation, “VBA Hello World Message Box Example Title”

The above MsgBox will show you Yes No Type message box with information icon and title.

VBA MessageBox Options and Uses

Let us see the different options and usage of Message Box Function. We can create verity of Message Boxes in VBA to handle different scenarios.

VBA MsgBox Styles

In Most cases we use vbYesNo Message Box and get the result to a variable. Let us see vbYesNo Syntax, arguments, parameters, yes no default buttons, yes no prompt and yes no examples. yes no if syntax helps us to decide based on the user input. We can check If yes no return, yes no answer.

MsgBox “This is the example Yes No Syntax”, vbYesNo

We can also create MsgBox with Yes No and Cancel values, and get the user yes, no or cancel responses. Instead of adding the stings in MsgBox Parameters. We can create variable string and pass as a string. We can use the variable for MsgBox Prompt or Title. Combining Yes No Button Types with different option, we can display yes no critical, yes no warning, yes no exclamation, yes no question type Msg Box. below arr syntax to change button caption, button labels, button names.

Here is the Example with Yes, No, Cancel and Exclamation Icon.

MsgBox “This is the example Yes No Cancel Syntax”, vbYesNoCancel + vbExclamation

We can use Userforms to create customized Message Boxes: MsgBox Without OK button, without buttons, no buttons to show prompt. We can use command buttons, radio buttons in UserForm. We can fortmat the text, Font Size, Font Color and set Bold text in MsgBox.

We can pass variable value or variable text create a string and use as MsgBox variable input for Prompt and Titles. Different buttons and icons of MsgBox are created for different purposes.

We can have multiple lines, access custom buttons, access new line, access carriage return, variable type, variable, error handling, on error goto, error message dialog box, display array, two lines, access multiple lines.

Excel VBA MsgBox Yes No Syntax

The following is the simple Example on VBA MsgBox Yes No Prompt Type. We can use this to receive the acceptance of user to certain criteria. And decide the further process.
MsgBox “This is the example Yes No Syntax”, vbYesNo

Check the below example, it will check if user clicked on Yes or No button. We can also show the Help when user pressing F1 button or Help button.

If MsgBox("Do you want to see know the current Time", vbYesNo) = vbYes Then MsgBox Format(Now(), "HH:MM:SS AMPM"), vbInformation, "Current Time" End If

VBA MsgBox Yes No If

The following example on vba msgbox yes no if to show the different messages boxes based on the selected option. If then and exit sub syntax helps terminate the sub procedure based on the certain condition.

Sub sbKnowingUserInput() intUserOption = MsgBox("Press Yes or No Button", vbYesNo) If vbOption = 6 Then MsgBox "You Pressed YES Option" ElseIf vbOption = 7 Then MsgBox "You Pressed NO Option" Else MsgBox "Nothing!" End If End Sub

VBA Message Box New line,carriage return, two lines, multiple line

We can use vbCr to split the message box text into a new line and add carriage return to make into two lines. We can use & vbCr to split the message into multiple lines.
MsgBox “Hello, This is Line ONE” & vbCr & “This is Line TWO”

VBA MsgBox Yes No Cancel Return

The below example on vba msgbox yes no cancel return to access the response of MsgBox. This will help us to access,store and input the msgbox response or string in variable value. We can use this variable text in the further programming.

Dim msgValue msgValue = MsgBox("Hello, Are you a graduate? Choos:" _ & vbCr & "Yes: if you are a graduate" _ & vbCr & "Yes: if you are Not a graduate" _ & vbCr & "Yes: if you are Not Intrested" _ , vbYesNoCancel + vbQuestion) If msgValue = vbYes Then MsgBox "You are eligible for applying for this Job" ElseIf msgValue = vbNo Then MsgBox "You are NOT eligible for applying for this Job" ElseIf msgValue = vbCancel Then MsgBox "No Problems, We will find suitable job for you" End If

VBA If Then MsgBox and Exit Sub

Some times we may want to ask user to continue further, other wise skip the execution of next program. The below example on VBA if then msgbox and exit sub will help you to do this:

Sub sbPressYesToExitSub() If MsgBox("Would you like to continue...?", vbQuestion + vbYesNo) <> vbYes Then Exit Sub End If 'The below statements will not be executed when your press Yes button. 'You can write the next programming steps here... This will execute if user selects No in the above prompt. MsgBox "You have not pressed Yes button" End Sub

VBA On Error GoTo Message Box for Error Handling

MsgBox is also useful in error handling. We can tell VBA error message on error. Or we can go to a label and show message box with error number and description. The below code will execute the code and show the error number and description if there is any run-time error.

Sub sbShowing_Error_MessageBox() On Erro GoTo ErrorHanMsg1 'Your code goes here.... Exit Sub 'This comes before End Sub or End Function Statement ErrorHanMsg1: MsgBox Err.Number & vbCr & Err.Description End Sub

VBA MsgBox Styles

Here are the list of styles and models of Message Box Function in VBA. We combine different options to display a message box with desired options.

Please find the following code and output. It will Display OK button only. When we click OK button, It will return value 1 as a output.

Code:
Sub MessageBox_vbOKOnly() 'Variable Declaration Dim OutPut As Integer 'Example of vbOKOnly OutPut = MsgBox("Thanks for visiting Analysistabs!", vbOKOnly, "Example of vbOKOnly") End Sub
Output:

Top

Please find the following code and output. It will Display OK and Cancel buttons. When we click OK button, It will return value 1 as a output.And When we click Cancel button, It will return value 2 as a output.

Code:
Sub MessageBox_vbOKCancel() 'Variable Declaration Dim OutPut As Integer 'Example of vbOKCancel OutPut = MsgBox("You are VBA Expert, is it True?", vbOKCancel, "Example of vbOKCancel") If OutPut = 1 Then 'Output = 1(Ok) MsgBox "Grate! You are VBA Expert, You can learn Advanced Our VBA!", , "Ok - 1" Else 'Output = 2(Cancel) MsgBox "You can Star Learning from Basics!", , "Cancel - 2" End If End Sub
Output:

Top

Please find the following code and output. It will Display Abort, Retry, and Ignore buttons. When we click Abort button, It will return value 3 as a output. When we click Retry button, It will return value 4 as a output.And When we click Ignore button, It will return value 5 as a output.

Code:
Sub MessageBox_vbAbortRetryIgnore() 'Variable Declaration Dim OutPut As Integer 'Example of vbAbortRetryIgnore OutPut = MsgBox("The Connection has failed. Do you want to Continue?", vbAbortRetryIgnore, "Example of vbAbortRetryIgnore") If OutPut = 3 Then 'Output = 1(Abort) MsgBox "Abort!", , "Abort - 3" ElseIf OutPut = 4 Then 'Output = 4(Retry) MsgBox "Retry!", , "Retry - 4" Else 'Output = 5(Ignore) MsgBox "Ignore!", , "Ignore - 5" End If End Sub
Output:

Top

Please find the following code and output. It will Display Yes, No, and Cancel buttons. When we click Yes button, It will return value 6 as a output. When we click No button, It will return value 7 as a output.And When we click Cancel button, It will return value 2 as a output.

Code:
Sub MessageBox_vbYesNoCancel() 'Variable Declaration Dim OutPut As Integer 'Example of vbYesNoCancel OutPut = MsgBox("File already exists. Do you want to replace?", vbYesNoCancel, "Example of vbYesNoCancel") If OutPut = 6 Then 'Output = 6(Yes) MsgBox "Yes!", vbInformation, "Yes - 6" ElseIf OutPut = 7 Then 'Output = 7(No) MsgBox "No!", vbInformation, "No - 7" Else 'Output = 2(Cancel) MsgBox "Cancel!", vbInformation, "Cancel - 2" End If End Sub
Output:

Top

Please find the following code and output.It will display Display Yes and No buttons. When we click Yes button, It will return value 6 as a output.And, When we click No button, It will return value 7 as a output.

Code:
Sub MessageBox_vbYesNo() 'Variable Declaration Dim OutPut As Integer 'Example of vbYesNo OutPut = MsgBox("Do you want to replace the existing file?", vbYesNo, "Example of vbYesNo") If OutPut = 6 Then 'Output = 6(Yes) MsgBox "Yes! Replace the file", vbInformation, "Yes - 6" Else 'Output = 7(No) MsgBox "No! Don't replace the file", , "No - 7" End If End Sub
Output:

Top

Please find the following code and output. It will Display Retry and Cancel buttons.When we click Retry button, It will return value 4 as a output.And, When we click Cancel button, It will return value 2 as a output.

Code:
Sub MessageBox_vbRetryCancel() 'Variable Declaration Dim OutPut As Integer 'MsgBox VBA Example of vbRetryCancel OutPut = MsgBox("Close the File.Try Again?", vbRetryCancel + vbDefaultButton2, "Example of vbRetryCancel") If OutPut = 4 Then 'Output = 4(Retry) MsgBox "Retry!", , "Retry - 4" Else 'Output = 2(Cancel) MsgBox "Cancel It!", , "Cancel - 2" End If End Sub
Output:

Top

Please find the following code and output. When we click Ok button, It will return value 1 as a output. And, It will display critical Message Icon.

Code:
Sub MessageBox_vbCritical() 'Variable Declaration Dim OutPut As Integer 'Example of vbCritical OutPut = MsgBox("Please enter valid Number!", vbCritical, "Example of vbCritical") End Sub
Output:

Top

Please find the following code and output.When we click Ok button, It will return value 1 as a output. And, It will display Warning Query icon.

Code:
Sub MessageBox_vbQuestion() 'Variable Declaration Dim OutPut As Integer 'Example of vbQuestion OutPut = MsgBox("Are you fresher?", vbQuestion, "Example of vbQuestion") End Sub
Output:

Top

Please find the following code and output.When we click Ok button, It will return value 1 as a output. And, It will display Warning Message icon.

Code:
Sub MessageBox_vbExclamation() 'Variable Declaration Dim OutPut As Integer 'Example of vbExclamation OutPut = MsgBox("Input Data is not valid!", vbExclamation, "Example of vbExclamation") End Sub
Output:

Top

Please find the following code and output.When we click Ok button, It will return value 1 as a output. And, It will display Information Message icon.

Code:
Sub MessageBox_vbInformation() 'Variable Declaration Dim OutPut As Integer 'Example of vbInformation OutPut = MsgBox("Succesessfully Completed the Task.", vbInformation, "Example of vbInformation") End Sub
Output:

Top

Please find the following code and output. By Default it will focus on first (Retry) Button. When we press enter it will result the value of Retry button as 4.

Code:
Sub MessageBox_vbDefaultButton1() 'Variable Declaration Dim OutPut As Integer 'Example of vbDefaultButton1 OutPut = MsgBox("Close the File.Try Again?", vbRetryCancel + vbDefaultButton1, "Example of vbDefaultButton1") End Sub
Output:

Top

Please find the following code and output.By Default it will focus on Second(Cancel) Button. When we press enter it will result the value of Retry button as 2.

Code:
Sub MessageBox_vbDefaultButton2() 'Variable Declaration Dim OutPut As Integer 'Example of vbDefaultButton2 OutPut = MsgBox("Close the File.Try Again?", vbRetryCancel + vbDefaultButton2, "Example of vbDefaultButton2") End Sub
Output:

Top

Please find the following code and output.By Default it will focus on Third(Cancel) Button. When we press enter it will result the value of Retry button as 2.

Code:
Sub MessageBox_vbDefaultButton3() 'Variable Declaration Dim OutPut As Integer 'Example of vbDefaultButton2 OutPut = MsgBox("Close the File.Try Again?", vbYesNoCancel + vbDefaultButton3, "Example of vbDefaultButton3") End Sub
Output:

Top

Please find the following code and output.The user must respond to the message box before continuing work in the current application.

Code:
Sub MessageBox_vbApplicationModal() 'Variable Declaration Dim OutPut As Integer 'Example of vbApplicationModal OutPut = MsgBox("Thanks for visiting Analysistabs!", vbApplicationModal, "Example of vbApplicationModal") End Sub
Output:

Top

Please find the following code and output.All applications are suspended until the user responds to the message box.

Code:
Sub MessageBox_vbSystemModal() 'Variable Declaration Dim OutPut As Integer 'Example of vbSystemModal OutPut = MsgBox("Thanks for visiting Analysistabs!", vbSystemModal, "Example of vbSystemModal") End Sub
Output:

Top

Please find the following code and output.Adds Help button to the message box.

Code:
Sub MessageBox_vbMsgBoxHelpButton() 'Variable Declaration Dim OutPut As Integer 'Example of vbMsgBoxHelpButton OutPut = MsgBox("Thanks for visiting Analysistabs!", vbMsgBoxHelpButton, "Example of vbMsgBoxHelpButton") End Sub
Output:

Top

Please find the following code and output.Specifies the message box window as the foreground window.

Code:
Sub MessageBox_VbMsgBoxSetForeground() 'Variable Declaration Dim OutPut As Integer 'Example of VbMsgBoxSetForeground OutPut = MsgBox("Thanks for visiting Analysistabs!", vbMsgBoxSetForeground, "Example of VbMsgBoxSetForeground") End Sub
Output:

Top

Please find the following code and output.Here text is right aligned.

Code:
Sub MessageBox_vbMsgBoxRight() 'Variable Declaration Dim OutPut As Integer 'Example of vbMsgBoxRight OutPut = MsgBox("Input Data is not valid!", vbMsgBoxRight, "Example of vbMsgBoxRight") End Sub
Output:

Top

Please find the following code and output.It Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

Code:
Sub MessageBox_vbMsgBoxRtlReading() 'Variable Declaration Dim OutPut As Integer 'Example of vbMsgBoxRtlReading OutPut = MsgBox("Thanks for visiting Analysistabs!", vbMsgBoxRtlReading, "Example of vbMsgBoxRtlReading") End Sub
Output:

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Double click on ThisWorkbook from Project Explorer
  4. Copy the above code and Paste in the code window
  5. Press F5
  6. You should see the above output

Custom Message Box in Excel VBA:

What if your requirement is not achievable with the available types of MessageBox. You Can create your own MessageBox using Forms in Excel VBA. You can design your own custom MessageBox using Form Controls.
Here is the example Custom MessageBox.

Top

MessageBox Constants in Excel VBA:

Please find the following table for button argument values:

Constant ValueDescription
vbOKOnly0It Display’s OK button only.
vbOKCancel1It Display’s OK and Cancel buttons.
vbAbortRetryIgnore2It Display’s Abort, Retry, and Ignore buttons.
vbYesNoCancel3It Display’s Yes, No, and Cancel buttons.
vbYesNo4It Display’s Yes and No buttons.
vbRetryCancel5It Display’s Retry and Cancel buttons.
vbCritical16It Display’s Critical Message icon.
vbQuestion32It Display’s Warning Query icon.
vbExclamation48It Display’s Warning Message icon.
vbInformation64It Display’s Information Message icon.
vbDefaultButton10Here first button is default.
vbDefaultButton2256Here second button is default.
vbDefaultButton3512Here third button is default.
vbDefaultButton4768Here fourth button is default.
vbApplicationModal0Application modal. The user must respond to the message box before continuing work in the current application.
vbSystemModal4096System modal. In this case all applications are suspended until the user responds to the message box.
vbMsgBoxHelpButton16384Adds Help button to the message box.
VbMsgBoxSetForeground65536Specifies the message box window as the foreground window.
vbMsgBoxRight524288Text is right aligned.
vbMsgBoxRtlReading1048576Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

 

Top

MessageBox Return Constants and Enumerations in Excel VBA:

ConstantValueDescription
vbOK1OK
vbCancel2Cancel
vbAbort3Abort
vbRetry4Retry
vbIgnore5Ignore
vbYes6Yes
vbNo7No

 

Top

Recommended Resource

LIMITED TIME OFFER - Get it Now!
Advanced Project Plan Excel Template

LIMITED TIME OFFER - Get it Now!
Business PowerPoint Presentations Templates Pack

 
 
Related ResourceExternal VBA Reference
Excel VBA ReferenceProject Management Reference
VBA Reference: Excel Reference:
  • Project Management Methodologies
  • MS Project Templates
  • Excel, Word, PowerPoint Timeline Templates
  • Excel, Word, PowerPoint Planners and Trackers
  • Microsoft Excel Templates
  • MS PowerPoint Excel Templates
  • MS Word Templates
  • MS Office Schedules Templates
  • Excel, Word, PowerPoint Agenda Templates
  • Excel, Word, PowerPoint Invoices Templates
  • Excel, Word, PowerPoint Business Plans Templates
  • Excel, Word, PowerPoint Financial Management Templates
  • Excel, Word, PowerPoint Minutes Templates
Details
Written by June Blender
Last Updated: 23 December 2016
Created: 15 December 2016
Hits: 7022

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

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:

  1. Use the msgbox or msgboxyesno snippets
  2. Replace the 'Text' placeholder with the text that appears in the message box.
  3. 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 Showstatic 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

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:

  1. Click the Designer tab and, in the Properties pane for the form, click the Event button (lightening icon).



  2. 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: 

 

 

 

If you have questions about our products, please post in our support forum.
For licensed customers, use the forum associated with your product in our Product Support Forums for Registered Customers.
For users of trial versions, please post in our Trial Software Questions forum.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *