Visual Basic/Basic Graphical User Interfaces

From Wikiversity
Jump to navigation Jump to search
This lesson is part of the course on Visual Basic. Previous lesson: Functions and Subroutines in VB6. Next lesson: Event-Driven Design in VB6.

This lesson will cover basic Graphical User Interface methods in Visual Basic. Before proceeding with this lesson, please ensure that you have read and understood all of the lessons from Topic:Visual Basic up until this point, with particular emphasis on Control Structures and Logical Expressions in VB6 and Functions and Subroutines in VB6.

Overview[edit]

At this point, you're probably saying to yourself, "I thought this was supposed to be Visual Basic!" Indeed, Visual Basic is very much so an interface-oriented language, far more than other languages, and designing even complex graphical user interfaces (or GUIs) is quite simple.

In contrast to traditional, command-line interfaces, almost all user interfaces in Visual Basic are constructed using the WIMP, or "windows, icon, menu, pointer," GUI style. This means that Visual Basic programs interact with users almost exclusively using graphical elements, such as windows, buttons, toolbars, etc., with very few console-based applications (in fact, creating a console-based VB application is quite difficult, requiring advanced API techniques, which will be covered much later). While in previous lessons, we've made use of Debug.Print, which is not a WIMP element, it's important to note that the debugging, or intermediate, window is only visible in design mode, and not during typical program execution.

In this lesson, we'll introduce and expand upon three basic methods of creating WIMP interfaces in Visual Basic: using the MsgBox function (which you've seen before), the InputBox function, and forms and controls.

MsgBox revisited[edit]

Up until now, we've blindly used this magical MsgBox function to display text without really understanding what it was, how it worked, or what could be done with it. Now that we have a bit more understanding of functions, subroutines, and control structures, let's take a somewhat closer look at it.

MsgBox is a actually a function, like many of the functions we've used and created before, provided by the standard VB runtime. Its function declaration is the following:

Public Function MsgBox( _
   ByVal prompt As String, _
   Optional ByVal buttons As Integer = vbOKOnly, _
   Optional ByVal title As String = Nothing _
   Optional ByVal helpfile As String = Nothing _
   Optional ByVal context As Integer = Nothing _
) As Integer

Having read Functions and Subroutines in VB6, you should now be able to recognize a few useful attributes of the MsgBox function. For one, MsgBox has a return type--Integer, which implies that we can not only display data in a MsgBox, but also get information back. The information we are able to retrieve from calling the MsgBox function is a numerical expression equating to a constant value that describes which button on the MsgBox was clicked. Legal return values for the MsgBox function are: vbOK, vbCancel, vbAbort, vbRetry, vbIgnore, vbYes, and vbNo.

Furthermore, we can specify which buttons and styles we want displayed on our message boxes using the "buttons" argument. If, for instance, we want to display a msgBox with the buttons "Abort," "Retry," and "Ignore," we can use the construct: MsgBox "Test", vbAbortRetryIgnore. If we further want to display this message box with a "Question" icon, we can use this construct: MsgBox "Test", vbAbortRetryIgnore + vbQuestion. There are many possible values for the button argument, and you can find a full list in the MSDN library.

With the title argument, we can also change the text we want to display in the caption of the message box by passing any legal String. The "helpfile" and "context" arguments will be explained later on in the course when we cover contextual help in VB6.

MsgBox examples[edit]

Now let's took a look at a simple example that makes use of MsgBox.

Public Sub Main()
    If MsgBox("Click a button.", vbOKCancel, "MsgBox Test") = vbOK Then
        MsgBox "You clicked OK!", vbOKOnly, "MsgBox Test"
    Else
        MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test"
    End If
End Sub

And voila! We have a program that's capable of responding to user input! Now what if we to give the user three different options? We could do this:

Public Sub Main()
    If MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test") = vbYes Then
        MsgBox "You clicked Yes!", vbOKOnly, "MsgBox Test"
    ElseIf MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test") = vbNo Then
        MsgBox "You clicked No!", vbOKOnly, "MsgBox Test"
    Else
        MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test"
    End If
End Sub

However, you may notice one major problem with this code: it displays two message boxes instead of just one, which is what we expected. This is because each time you call MsgBox, a new message box is created. To respond to three different return types for one MsgBox, it's best to store the value in a variable and then perform tests on that variable. For example:

Public Sub Main()
    Dim ret As Integer

    ret = MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test")
    If ret = vbYes Then
        MsgBox "You clicked Yes!", vbOKOnly, "MsgBox Test"
    ElseIf ret = vbNo Then
        MsgBox "You clicked No!", vbOKOnly, "MsgBox Test"
    Else
        MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test"
    End If
End Sub

InputBox[edit]

Now let's take a quick look at a function similar to MsgBox that allows the user to provide a much, much wider array of valid inputs, namely the InputBox function. This function is provided by the standard VB6 runtime, and its declaration is as follows:

Public Function InputBox( _
    prompt As String, _
    Optional title As String = Empty, _
    Optional default As String = "", _
    Optional xpos As Single = Empty, _
    Optional ypos As Single = Empty, _
    Optional helpfile As String = Empty, _
    Optional context As Integer = 0 _
) As String

This function displays an InputBox, or a single dialog requesting a single line of ASCII input from the user, with the given prompt, title, default text (specified by default), and other argument values (which we won't get into in depth) and returns the String that the user provided the dialog. Let's take a look at a simple example:

Public Sub Main()
    Dim YourName As String

    YourName = InputBox("Please enter your name.", "InputBox demo")
    
    If Len(YourName) > 0 Then
        MsgBox "Your name is " + YourName
    Else
        MsgBox "You hit cancel or entered an empty string."
    End If
End Sub

This simple little program prompts the user for his or her name and then displays it in a MsgBox. If the user selected cancel the string returned will be an empty string (""). This very simple function now allows your program to behave in an infinite number of ways, as the InputBox dialog can accept an infinite number of various inputs.

Forms and controls[edit]

In Introduction to VB6, you gained some basic knowledge of forms and controls. In this section, we'll attempt to expand upon that knowledge by discussing basic control-based GUI design, looking at some common controls, and introducing the properties of controls.

Forms[edit]

In Visual Basic, the Form is the primary component of every GUI application. A form is a unique kind of control, known as a top-level container, a control that can contain within it any number of controls but that cannot itself be contained by other containers. Forms can come in many shapes and sizes (we'll learn about modifying the appearance of forms a bit later), but typically they are solid gray boxes with a surrounding frame, a caption bar, and a variety of clip controls (a context menu, a close button, a minimize button, etc.) Forms can be created quite easily by starting a new project and selecting "Add Form..." from the project menu. If you specify this form as your project's start-up object (from Project / Properties), when you run this code, your form will appear, and the program will end when the form is closed.

Properties of forms[edit]

Like all controls, forms have a variety of properties associated with them. Some of these properties can be set at runtime (which we'll cover later) or by modifying them in the Properties Window. To access the Properties Window, simply select the Form (in design mode, of course), and you should see the properties for the form appear in the right-most docking-window directly beneath the Project Explorer. From here, you can change almost every property of your form.

The most important property of a form is its Name. This property can be set only at design, and should appear as the first item in the properties list. You can set this to anything you want; however, it is common convention that all form names begin with a form identifier, such as "Form" or "frm". By default, the first form in a project is named "Form1," the second "Form2," etc. Choosing a clear, descriptive name for your forms is very important because everytime you call methods on or change the properties of a form from runtime, you will use the form's name as an identifier.

Another important property of a form is its Caption. This property specifies what text will be displayed in the form's caption bar. You can change it by selecting "Caption" from the properties list, and then specifying any single line of text you would like. You can adjust the width and height of your forms by either explicitly specifying the property in the Properties Window or by simply resizing the form in design mode. There are many other physical properties of forms that we won't get into here, but please, feel free to play around with them.

Form modules[edit]

So far, every VB6 application we've dealt with has been executed from a Basic module (or .bas file), by creating a project, adding a new module, and adding to that module a Public Sub Main(). In traditional BASIC, all programs were constructed this way; however, with the advent of Visual Basic a new kind of module, known as a form module, was introduced. A form module is a unique kind of module that contains code that is owned by one, and only one, form. Every form has one, and only one, form module associated with it, and form modules contain all of the code that can be directly invoked by the form or by controls contained by the form in response to an action by the user. The code in these modules can only be accessed once the form is constructed, and form modules typically contain primarily only Private subroutines and functions, though they may also contain Public helper routines to allow accessibility to components of the form to other modules.

To access a form's code module, simply select the form in the Project Explorer, right-click, and select "View Code." This will open up an empty editor window like we're used to seeing with Basic modules--the only difference is what we can put in a form module. The most common starting point for a form is Private Sub Form_Load(). This routine is called immediately after the form is created and drawn, but before the form has begun waiting for user input. To start, let's try rewriting an example you've seen before to use Form_Load() instead of Main():

Private Sub Form_Load()
    MsgBox "Hello, world!"
End Sub

Immediately after this form is loaded, a MsgBox will be displayed with the text "Hello, world!". It is important to note that every form can have a Private Sub Form_Load() and that, unlike with Sub Main, the Form_Load routine can be accessed only by the form module (due to its Private access).

The "Me" identifier[edit]

Now let's say we want to access the properties and methods of our form from within our form module. We could use something like Form1.Caption = "Hello, world!", but this is very bad practice, as you'll understand fully once we begin dealing with ActiveX controls and control arrays (much later on!). Instead, Visual Basic provides an identifier known as the "Me" identifier, which is similar to "this" in languages such as C and Java. It allows us, basically, to access ourselves--that is, the form module it's used in. For example:

Private Sub Form_Load()
    Me.Caption = "Hello, world!"
End Sub

This will change the Form's caption to "Hello, world!" after the form is loaded, regardless of what property we specified at design-time.

A simple GUI program[edit]


Learning Visual Basic
Previous: Visual Basic/Functions and SubroutinesNext: Visual Basic/Event-Driven Design