A message box is a predefined dialog box that displays application-related information to the user. Message boxes are also used to request information from the user.
To display information to the user in a message box
The following code demonstrates how to call the Show method of the MessageBox class to display information to the user. The call to the Show method uses the optional Style parameter to specify the type of icon to display in the message box that best fits the type of message box being displayed:
[Visual Basic] Public Sub PerformCalculations() 'Code is entered here that performs a calculation 'Display a message box informing the user that the calculations ' are complete MessageBox.Show "The calculations are complete", "My Application" _ , MessageBox.IconInformation End Sub [C#] public void PerformCalculations() { // Code is entered here that performs a calculation // Display a message box informing the user that the calculations // are complete MessageBox.Show ("The calculations are complete", "My Application", MessageBox.IconInformation); }
Message boxes can also receive input. The Show method of the MessageBox class returns a value that can be used to determine a choice made by the user. You can store this value in an Integer variable type or compare the value returned when you display the message box using an If statement. The Style parameter of the Show method can be set to display the proper buttons to ask a user for information.
To display a message box to request information
The following code demonstrates how to call the MessageBox method to retrieve information from the user and then determine the value that was selected:
[Visual Basic] Public Sub ExitApplication() 'Display a message box asking users if they want to exit the 'application. If MessageBox.Show ("Do you want to exit?", "My Application", _ MessageBox.YesNo + MessageBox.IconQuestion) _ = DialogResult.Yes Then Application.Exit End If End Sub [C#] public void ExitApplication(){ // Display a message box asking users if they want to exit the // application. if (MessageBox.Show ("Do you want to exit?", "My Application", MessageBox.YesNo + MessageBox.IconQuestion) == DialogResult.Yes) { Application.Exit(); } }
Dialog Boxes | MessageBox Class | DialogResult Class | Creating Dialog Boxes | Displaying Dialog Boxes for Win Forms