The Visual Basic Message Box

Introduction

The Visual Basic language, through its own library, provides a good and easy way to create a message box.

You may know already that if you want to use the Visual Basic language in your C# Visual Studio 2022 project, you can just type the Visual Basic class that contains the function you want to use, such as Interaction, followed by a period, and the method you want (if you are using a previous version of Microsoft Visual Studio, you may have to first add a reference to the Microsoft.VisualBasic.dll to your project (to the References node of the Solution Explorer)).

To support message boxes, the Visual Basic language provides a function named MsgBox that is a member of the Interaction static class.

Practical LearningPractical Learning: Starting a Project

  1. Start Microsoft Visual Studio
  2. In the Visual Studio 2022 dialog box, click Create a New Project
  3. In the Create a New Project wizard page, in the list of projects templates, click Windows Forms App
  4. Click Next
  5. In the Configure Your New Project wizard page, change the Project Name to VisualBasicMessageBoxes
    Accept or change the project Location
  6. Click Next
  7. In the Framework combo box, select the highest version (.NET 9.0 (Standard Term Support)).
    Click Create
  8. From the Toolbox, in the Common Controls section, click Button and click the form
  9. In the Properties window, change the characteristics of the button as follows:
    (Name): btnMessageBox
    Text:   Message Box
  10. Double-click the button to generate its Click event
  11. To execute, on the main menu, click Debug -> Start Without Debugging:
  12. Close the form and return to your programming environment
Author Note

Author Note

If you want, using the form of the application you created, you can apply the descriptions in the following sections to experiment with, and get, the same results.

The Message of a Message Box

The primary way to get a message box in the Visual Basic language is to pass a string to the Interaction.MsgBox() function. Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            Interaction.MsgBox("In this company, printing is not allowed for just anybody. " +
                               "Since you are a 'nobody', if you need to print, " +
                               "please send a special request to the IT department.");
        }
    }
}

This would produce:

A Simbple Visual Basic Message Box

Returning a Value from a Message Box

Remember that a message box can be used to ask a question to a user who would answer by clicking a button. To support the answer of a question, the Interaction.MsgBox() function of the Visual Basic language returns a member of an enumeration named MsgBoxResult.

The value returned by a message box corresponds to a button the user would have clicked (on the message box). The return value of the MsgBox() function is based on the MsgBoxResult enumeration. The buttons and the returned values are as follows:

If the User Clicks Button Caption Integral Value
OK OK 1
Cancel Cancel 2
Abort Abort 3
Retry Retry 4
Ignore Ignore 5
Yes Yes 6
No No 7

Options on Creating a Message Box

The Buttons of a Message Box

To let a user make a decision, a message box can be made to display one or more buttons. In the Visual Basic language, the buttons of the message box are controlled by an enumeration named MsgBoxStyle. The members of this enumeration are:

Message Box Buttons MessageBoxButtons MsgBoxStyle
OK OK OKOnly 0
OKCancel OKCancel OKCancel 1
Yes YesNo YesNo 4
Yes No Cancel YesNoCancel YesNoCancel 3
Retry Cancel RetryCancel RetryCancel 5
Abort Retry Ignore AbortRetryIgnore AbortRetryIgnore 2

To specify the button(s) you want, pass a second argument as MsgBoxStyle, a period, and the option you want. Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            Interaction.MsgBox("Please submit your time sheet.", MsgBoxStyle.OkOnly);
        }
    }
}

This would produce:

Message Box With Buttons

The Icon of a Message Box

We already know that, to enhance the appearance of a message box, you can display an icon on it. To support icons, the MsgBoxStyle enumeration provides the following additional members:

To Display MsgBoxStyle Integral Value
Critical Critical 16
Question Question 32
Exclamation Exclamation 48
Information Information 64

To apply one of these buttons, combine its style with that of the button, using the | operator (OR). Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            Interaction.MsgBox("Are you ready to provide your credit card information?",
                               MsgBoxStyle.YesNoCancel | MsgBoxStyle.Question);
        }
    }
}

This would produce:

Message Box With an Icon

The Default Button of a Message Box

We already know that when a message box is configured to display more than one button, the operating system is set to decide which button is the default. If a message box has more than one button, you can decide what button would be the default. To support the default button, the MsgBoxStyle enumeration provides the following additional members:

MsgBoxStyle Integral Value If the message box contains more than one button, the default button would be
DefaultButton1 0 the first
DefaultButton2 256 the second
DefaultButton3 512 the third

Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            Interaction.MsgBox("Are you ready to provide your credit card information?",
                               MsgBoxStyle.YesNoCancel | MsgBoxStyle.Question | MsgBoxStyle.DefaultButton2);
        }
    }
}

Message Box With a Default Button

The Caption of a Message Box

Notice that the Visual Basic message boxes we have used so far displayed the name of a library in their title bar. Fortunately, the MsgBox() function allows you to specify a caption for the message box. In fact, the syntax of the MsgBox() function is:

public static MsgBoxResult MsgBox(object Prompt,
                                  Microsoft.VisualBasic.MsgBoxStyle Buttons = Microsoft.VisualBasic.MsgBoxStyle.OkOnly,
                                  object? Title = default);

Based on this syntax, the first argument is the message to display to the user. The second argument is the MsgBoxStyle values that we saw already. Notice that the second argument is optional. The third argument, also optional, is the value that will display on the title bar of the message box. You can pass that argument as a string. Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            Interaction.MsgBox("When you complete the test, " +
                               "make sure the examiner confirms your completion.", 0, "Monthly Test");
        }
    }
}

Fundamentals of an Input Box

Introduction

An input box is a specially designed dialog box that allows the programmer to request a value from the user and use that value as necessary. An input box displays a title, a message to indicate the requested value, a text box for the user to type a value, and two buttons: OK and Cancel. Here is an example:

Input Box

When an input box displays, it presents a request to the user who can then provide a value. After using the input box, the user can change his or her mind and press Esc or click Cancel to dismiss the input box. If the user provided a value and wants to acknowledge it, he or she can click OK or press Enter. This would transfer the contents of the text box to the application that displayed the input box.

Creating an Input Box

To support input boxes, the Visual Basic library provides a function named InputBox. As seen for the message box, if you are working in a .NET project and you are using a language other than Visual Basic, the InputBox is defined in the Interation static class. Therefore, to display an input box, call the Interation.InputBox() method and pass a string to it. Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            Interaction.InputBox("Type the Student's age (as a positive number):");
        }
    }
}

This would produce

Input Box

The Caption of an Input Box

Notice that the above input box displays the name of a library in its title bar. If you want your input box to display a title of your choice, pass a second argument to the Interaction.InputBox() function. You can pass the argument as a simple string. Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            Interaction.InputBox("Type the Student's age (as a positive number):",
                                 "Summer Camp Registration");
        }
    }
}

This would produce

The Caption of an Input Box

Details on Using an Input Box

The Return Value of an Input Box

As seen for a message box, one of the goals of an input box is to present a request to a user. After a user has typed a value in the text box and clicks OK or presses Enter, the Interaction.InputBox() function produces the value that the user provided. As it happens, the Interaction.InputBox() function returns a string. You can then use that returned value any way you want. Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            string strAccountName = Interaction.InputBox("Enter Account Name:",
                                                         "Summer Camp Registration");

            MessageBox.Show($"Member Name: {strAccountName}",
                             "Summer Camp Registration");
        }
    }
}

Of course, you can request any value from the user. If the user provides a value other that a string, you must first convert it to the right type before using it. Here is an example:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            string strEmployeeName = Interaction.InputBox("Enter Employee Name:",
                                                         "Summer Camp Registration");
            string strHourlySalary = Interaction.InputBox("Enter the Hourly Salary:",
                                                         "Summer Camp Registration");
            double sal = double.Parse(strHourlySalary);

            string strSummary = "Employment Summary";
            strSummary += Environment.NewLine;
            strSummary += "________________________________________";
            strSummary += Environment.NewLine;
            strSummary += $"Employee Name:\t{strEmployeeName}";
            strSummary += Environment.NewLine;
            strSummary += $"Hourly Salary:\t{sal}";
            strSummary += Environment.NewLine;
            strSummary += $"Biweekly Salary:\t{sal * 40 * 2:f}";
            strSummary += Environment.NewLine;
            strSummary += $"Monthly Salary:\t{sal * 40 * 4:F}";
            strSummary += Environment.NewLine;
            strSummary += $"Yearly Salary:\t{sal * 40 * 4 * 12:f}";
            strSummary += Environment.NewLine;
            strSummary += "========================";
            MessageBox.Show(strSummary,
                            "Summer Camp Registration");
        }
    }
}

Here is an example of running the application:

Visual Basic Input Boxes

Visual Basic Input Boxes

Visual Basic Input Boxes

A Default Value for an Input Box

When displaying an input box, you can assist the user to know the type of value you are expecting in the text box. The type of information the user is supposed to provide depen. To assist the user with the type of value you are expecting, you can give an example or a type. To do this, pass a third argument as a string. When passing it, you can provide a sample value that the user would follow. Here are examples:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            string strEmployeeName = Interaction.InputBox("Enter Employee Name:",
                                                         "Employment Application",
                                                         "John Doe");
            string strDateHired = Interaction.InputBox("Enter the date the employee was hired:",
                                                       "Date Verification",
                                                       "MM/DD/YYYY");
            string strHourlySalary = Interaction.InputBox("Enter the Hourly Salary:",
                                                          "Company Benefits",
                                                          "20.00");
            double sal = double.Parse(strHourlySalary);

            string strSummary = "Employment Summary";
            strSummary += Environment.NewLine;
            strSummary += "________________________________________";
            strSummary += Environment.NewLine;
            strSummary += $"Employee Name:\t{strEmployeeName}";
            strSummary += Environment.NewLine;
            strSummary += $"Date Hired:\t{strDateHired}";
            strSummary += Environment.NewLine;
            strSummary += $"Hourly Salary:\t{sal}";
            strSummary += Environment.NewLine;
            strSummary += $"Biweekly Salary:\t{sal * 40 * 2:f}";
            strSummary += Environment.NewLine;
            strSummary += $"Monthly Salary:\t{sal * 40 * 4:F}";
            strSummary += Environment.NewLine;
            strSummary += $"Yearly Salary:\t{sal * 40 * 4 * 12:f}";
            strSummary += Environment.NewLine;
            strSummary += "========================";
            MessageBox.Show(strSummary,
                            "Summer Camp Registration");
        }
    }
}

Here is an example of running the program:

Input Box - A Default Value

Input Box - A Default Value

Visual Basic Input Boxes

The Position of an Input Box

So far, we have been calling the Interaction.InputBox() without caring what it looks like. Actually, the syntax of this function is:

public static string InputBox(string Prompt,
                              string Title = "",
                              string DefaultResponse = "",
                              int Xpos = -1,
                              int YPos = -1);

By default, an input box displays in the center of the main monitor the user is using. Microsoft Visual Basic allows you to position your input box by specifying its corrdinates. To do this, pass of the last two arguments or both of them. The XPos value will be, in poxels, the distance from the left border of the monitor to the left border of the input box. The YPos value will be, in poxels, the distance from the top border of the monitor to the top border of the input box. Here are examples of calling the Interaction.InputBox() function and specifying the position of the input boxes:

using Microsoft.VisualBasic;

namespace VisualBasicMessageBoxes
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMessageBox_Click(object o, EventArgs e)
        {
            string strEmployeeName = Interaction.InputBox("Enter Employee Name:",
                                                         "Employment Application",
                                                         "John Doe", 600, 400);
            string strDateHired = Interaction.InputBox("Enter the date the employee was hired:",
                                                       "Date Verification",
                                                       "MM/DD/YYYY", 400, 800);
            string strHourlySalary = Interaction.InputBox("Enter the Hourly Salary:",
                                                           "Company Benefits",
                                                           "20.00", 500, 500);
            double sal = double.Parse(strHourlySalary);

            string strSummary = "Employment Summary";
            strSummary += Environment.NewLine;
            strSummary += "________________________________________";
            strSummary += Environment.NewLine;
            strSummary += $"Employee Name:\t{strEmployeeName}";
            strSummary += Environment.NewLine;
            strSummary += $"Date Hired:\t{strDateHired}";
            strSummary += Environment.NewLine;
            strSummary += $"Hourly Salary:\t{sal}";
            strSummary += Environment.NewLine;
            strSummary += $"Biweekly Salary:\t{sal * 40 * 2:f}";
            strSummary += Environment.NewLine;
            strSummary += $"Monthly Salary:\t{sal * 40 * 4:F}";
            strSummary += Environment.NewLine;
            strSummary += $"Yearly Salary:\t{sal * 40 * 4 * 12:f}";
            strSummary += Environment.NewLine;
            strSummary += "========================";
            MessageBox.Show(strSummary,
                            "Summer Camp Registration");
        }
    }
}

The Win32 Message Boxes

Introduction

The primary way the Microsoft Windows operating systems support message boxes is through its own Win32 library.

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2001-2025, FunctionX Thursday 08 May 2025, 08:13 Next