Forms and message boxes
Difficulty:   Lessons: 1, 2, 3, 4

by Lorenzo Dalla Vecchia

Message Boxes

You will now learn how to manage a simple, but important, function: message boxes.
You should be already familiar with those little popup message boxes, because they are very often encountered in the Windows environment.

Although I didn't explain them in detail, we already used simple message boxes in the previous examples. To implement them, you used the MsgBox command; right now, we can assume it has the following syntax:

    MsgBox "message string"

Were "message string" can be replaced with any string or string variable.
Example:

    MsgBox "This is a test message box. Hit OK to close it."

Wouldn't have been nicer if we could split the text in two lines? This can be done by concatenating the two strings with the vbCr (carriage-return) constant.

MsgBox "This is a text message box." & vbCr & "Hit OK to close it."

Maybe it isn't that useful with such a simple text, but, when you'll have to operate with longer captions or lists, it will be.

Simple, uh? It is important to remember that a message box is not a form: you can't put controls or attach code to it. But, as we are going to see, you can change its look and behaviour.

Advanced & multiple-choice message boxes

Pop-up message boxes can do a bit more than just presenting the user a message and letting him click OK.
For example, they can have an icon identifying the type of message being displayed. To use icons we need to go deeper into the knowledge of the MsgBox command syntax:

    MsgBox "message string", [appearance]

The new [appearance]thing is an optional (as indicated by the square brackets in the syntax) parameter to enhance the MsgBox instruction.
[appearance]is a numeric-type (Integer) parameter, whose value must match one of those given in the table below.

Constant name Value Icon Use
vbCritical 16

Used for critical messages and errors with the program.
(i.e. The file you are trying to open is corrupt!)
vbQuestion 32

Used when asking the user a question.
(i.e. Do you want to do a sound test now?)
vbExclamation 48

Used for important messages/questions
(i.e. Do you want to save the file?)
vbInformation 64

Used for generic, non-critical, informative messages.
(i.e. Keyword search completed. Found 4 matches.)

You can either use the numeric value or the constant name according to which is more comfortable to you. The following two lines of codes are both acceptable and they produce the same result:

    MsgBox "Critical error!", vbCritical

    MsgBox "Critical error!", 16

As you see, this is all very easy. Now, try typing and executing the following code:

    MsgBox "Do you want to exit the program?", vbQuestion

The result is a message box with the "question" icon but with just a single "OK" button. Why there isn't a couple of "Yes/No" buttons? That's because the 4 previously studied constants apply only to icons.
Buttons have their own set of specific constants, listed below.

Constant name Value Buttons displayed
vbOKCancel 1 OK, Cancel
vbAbortRetryIgnore 2 Abort, Retry, Ignore
vbYesNoCancel 3 Yes, No, Cancel
vbYesNo 4 Yes, No
vbRetryCancel 5 Retry, Cancel

Referring to the previous example, we need the vbYesNo constant, whose value is 4. Because we also need the vbQuestion constant for the icon, we need to add up the two constants with a plus (+) operator. If you are going to use values instead of constant names, you can type their sum directly.

    MsgBox "Do you want to exit the program?", vbQuestion + vbYesNo

    MsgBox "Do you want to exit the program?", 32 + 4

    MsgBox "Do you want to exit the program?", 36

The above code pieces are all equivalent and acceptable; the result is shown on the right.

Now we can show a question message with proper answers ("Yes" and "No"), but how can we find out which button was clicked by the user?
Until now, you used MsgBox as an instruction: you passed it parameters (message, icons, buttons) and it did something (showing the message), right? Well, it's time to learn that MsgBox can also be used as a function, and that means it returns a value; and this value represents the clicked button.
The following is the MsgBox function syntax:

    variable = MsgBox(message-string, [appearance])

variable is an Integer variable used by MsgBox to store the value of the clicked button.
The value of variable can then be compared with those in the following table.

Constant name Value Button clicked
vbOK 1 The user chose "OK"
vbCancel 2 The user chose "Cancel"
vbAbort 3 The user chose "Abort"
vbRetry 4 The user chose "Retry"
vbIgnore 5 The user chose "Ignore"
vbYes 6 The user chose "Yes"
vbNo 7 The user chose "No"

Here's a code example:

    Dim BtnValue As Integer
    'We'll use this to store the return value of MsgBox
   
    'Let's show the message box and get the answer
    BtnValue = MsgBox("Choose a button.", vbAbortRetryIgnore)
    'Examine the return value by comparing it with constants
    'and show consequent messages

    If BtnValue = vbAbort Then MsgBox "You clicked Abort."
    If BtnValue = vbRetry Then MsgBox "You clicked Retry."
    If BtnValue = vbIgnore Yhen MsgBox "You clicked Ignore."

As you can see, the above code shows the use of MsgBox both as a function (2nd line) and an instruction (last 3 lines).
Be careful not to compare the value of MsgBox directly! The following code...

    If MsgBox("Choose a button.", vbAbortRetryIgnore) = vbAbort _
     Then
MsgBox "You clicked Abort."
    If MsgBox("Choose a button.", vbAbortRetryIgnore) = vbRetry _
     Then
MsgBox "You clicked Retry."
    If MsgBox("Choose a button.", vbAbortRetryIgnore) = vbIgnore _
     Yhen
MsgBox "You clicked Ignore."

... wouldn't have worked properly, because it would have shown three message boxes instead of one. However, you can compare MsgBox directly to its constants if you need to test a single button (as we'll see in the next example).

The last, very simple, thing I want to tell you about message boxes is how to change their title caption. This can be done by specifying a third parameter in the function/instruction, whose definitive syntax is the following:

    variable = MsgBox(message-string, [appearance], [title-string])

    MsgBox message-string, [appearance], [title-string]

For example:

    BtnValue = MsgBox("Save current file?", vbYesNo, "Quit program")

If we don't need the [appearance] parameter, we can remove it and just type two consecutive commas:

    MsgBox "Found 2 files.", , "File search complete"

Simple, right? Now we will see a last example that will involve all the things you learned about message boxes and the QueryUnload event from the previous lesson.
Each time the user tries to close a form, we want a message box to show up asking him for consent. Because this is something we want to happen just before the unloading of the form, we won't use the Unload event procedure, but the QueryUnload event procedure. As you know from the previous lesson, the QueryUnload event of a form is fired each time the form is being closed (i.e. through the close button).
The code we need is the following:

    If MsgBox("Are you sure you want to exit?, vbQuestion) = vbNo Then
        Cancel = 1
    End If

As you can see, this time we directly compare the MsgBox function with the vbNo constant: we can do that because we are testing only a single button. Otherwise, we would have needed to store the return value in a variable and test the variable.
Note the
Cancel thing: it is a parameter of the QueryUnload event: if it is left to its initial value, 0, the form is unloaded, but if it is set to a value other than 0, the QueyUnload event is stopped. In our case, if the user clicks "Yes", Cancel is left to 0 and the form is unloaded, but, if he clicks "No", Cancel is set to 1 and the form is prevented from unloading.
Now try running the program and clicking on the close button of the form.

Conclusion

Ok, this second tutorial is over. I know the topic of forms can be boring for the newbie programmer, but the tutorial you have just finished reading contains base information that all programmers should acquire, such as the use of events.

Some other generic tutorials will follow in the immediate future, but I am also planning to release a lot of specific and interesting tutorials on things such as the use of files, images, help system, game programming and more.
Feel free to send me suggestions and feedback: as always, they are welcome!

Lesson 3

Your feedback/requests about tutorials?
Let me know! Click here.

Click Here!


Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
To contact the Webmaster, click here.
Hosted by InWind: www.inwind.it