Visual Basic GUI -
Controls, Events, and Interaction
© Morris Firebaugh
Recall the two characteristics of the Visual Basic language:
- Visual --> The GUI (Forms, Controls, Text boxes, Buttons, Tool boxes,...)
- Basic --> The syntax of BASIC code (That make the controls "play")
Graphical user interface design rests firmly on the foundation of OOP and illustrates its power and elegance. Some of the most important OOP concepts are listed below.
- Objects These are defined as data and the closely associated actions which operate on the data. This integration of data and opera-tions into a single object is called encapsulation. In GUI design, objects are abstracted as icons and menus which represent folders, files, application programs, processes, and operations.
- Messages These are defined as the requests sent to an object to execute the actions of which it is capable. Different objects may support different messages and may respond identically or differently to the same message. In GUI design, messages may be sent by the mouse in performing actions such as selection, launching, copying, restructuring, trashing, and ejecting. Messages commanding actions of saving, duplicating, printing, cutting, copying, and pasting may be sent via either the mouse or keyboard. The same message may cause different actions in different iconsa single click selects some icons and opens others.
- Methods These are the routines and algorithms for implementing messages. In GUI design, methods are implemented by high-level routines supported by the event manager, windows manager, menu manager, and so on.
- Class hierarchy Each object belongs to a class and is called an instance of the class. Class hierarchy provides for superclasses and subclasses. All objects of a subclass inherit the data and behavior defined by the superclass of which they are members. The class without a superclass is called the root class. A given class supports certain methods common to all members of the class. In GUI design, classes exist for data files, applications programs, menu headers, and menu selection items.
- Inheritance Membership in a class provides inheritance of data and methods for all members of the class. Members of a subclass inherit all the instance variables and methods of its superclass unless it chooses to override them with local variables and/or methods. Inheritance provides advantages of reducing data redundancy and action code duplication. In GUI design, all data icons share the method of examining their own creator slot and searching for the application program it points to when they are opened.
- Polymorphism Literally multiple forms, this feature of OOP means that the same message may be sent to objects of different classes. The response from members of distinct classes may be identical to, similar to, or completely distinct from each other, depending on the method chosen by each class for implementing the message.
- Computer graphics has served as the test bed for many of the original OOP concepts. SmallTalk, the seminal OOP language, was written at Xerox PARC, the origin of the WIMP GUI. It should not come as a surprise to students of computer graphics that the most successful GUIs rely most heavily on OOP.
- Alan Kay, father of the personal computer, helped invent OOP with the language SmallTalk.
Graphical Summary of OOP Concept
Objects in Visual Basic
The following are examples of the types of objects available in Visual Basic.
Controls on a form, such as a command buttons and frames, are objects.
Each form in a Visual Basic project is a separate object.
Databases are objects, and contain other objects, like fields and indexes.
A chart is MS Excel is an object
All objects are created as identical copies of their class
Each object of a class shares a common set of characteristics and capabilities (properties, methods, and events).
Two Visual Basic Objects:
a Form (called Form1)
a CommandButton (called Launch)
- Two objects are shown on the left, and one (CommandButton) is selected
- The CommandButton properties are shown on the right, with Class = CommandButton and Name property =Launch
Principles of GUI Design
Several of the principles of good GUI design evolved from systematic studies of strategies for effective human-computer interaction.
- Sensitivity Perhaps the first principle of good GUI design is the sensitivity to good design in general. Good design involves building smooth, effective, and unobtrusive interfaces between humans and the objects with which they interact. Good design is often most evident when it is missing. Remember DOS's "Abort, Retry,Fail?" and Mac's "trash this file" & "Eject that disk"?
- Task Understanding The first step in effective GUI/application program design is to achieve a thorough understanding of the task for which the program is being designed. This involves not only an analysis of the task mechanics, but a study of users, their background and skills, the environment in which the task is accomplished, the institutional setting, and communications requirements. The task analysis should be user-centered, with user interviews and interaction at every level of the development. Complete task understanding evolves through successive refinement as feedback is obtained from users interacting with prototype systems.
- Transparency The goal of an effective GUI/application program is to make the computer "invisible" and to focus the users complete attention on the task to be accomplished. In a perfectly designed GUI/application program, the user should be aware only of the work in progress and totally unaware of the tools s/he is using to perform the work. To the extent that the user must withdraw attention from the task at hand and ask, "Now lets see, how do I perform the next step?", the GUI/application program has failed the transparency principle.
- Integration The goal of good GUI design for application programs is the seamless integration of the GUI with the application program. There is nothing quite as obvious or awkward as a command-line program onto which a GUI has been pasted. The integration of a GUI with an application program does not involve simply replacing the command interpreter with a menu window, but rather requires a complete restructuring of the application program. This restructuring should be guided by the intuitive approach used by practitioners in the field, and should involve good psychological, artistic, and engineering design.
- Consistency In the design of GUI/application programs for general users who are likely to be users of other programs, consistency of metaphor is of great value. The genius of the desktop metaphor is that, once the user has mastered a single program, it is relatively easy to master subsequent programs. The closer the designer sticks to a consistent metaphor, the greater is the transference of skills for novice users.
- Feedback Effective feedback is an important principle in the design of any interface and particularly important in the rich environment possible with GUIs. Graphical feedback should indicate the status of the system at all times ("Wait, Im busy computing" or "Alright, what should we do next?"), the action options available to the user, an indication of what objects are active or selected, and an indication of the progress in time-consuming tasks like file copying. By simply switching the active cursor to a moving watch or hour-glass, the GUI informs the user, "Stand by while I complete the task you just assigned me." Well-designed feedback should give the user a feeling of control of all aspects of the application.
- Balance A well-designed GUI/application program must balance simplicity against features. There is tremendous pressure in the market place to match and surpass the feature list of the competitors products in each new release of a product. Soon, even a well-designed GUI becomes overloaded and cumbersome. Each menu item has submenus which, in turn, may have items with submenus and so on, with a decrease in transparency at each level. While such feature-rich programs may appeal to "power users," the loss of simplicity may leave the average user confused and overwhelmed.
General Visual Basic Approach to GUI Design
1. Construct the graphical objects that make up the user interface.
2. Define attributes for the objects to customize their appearance and behavior.
3. Embed code in each object to define methods for implementing its messages.
Intrinsic Controls in VB
Recall the basic default module which appears when a project is opened as a "StandardEXE" is the Form. Forms are the "containers" for the controls which constitute the basic objects of the GUI. There are three broad categories of VB controls:
- Intrinsic controls - These are the default toolbox list of controls.
- ActiveX controls - These are optional controls which may be added to the toolbox list, some of which are available only in the Professional and Enterprise editions.
- Insertable Objects - These are external objects such as MS Excel worksheets and MS Project Calendar which may be added to the toolbox.
VB Object Hierarchy
What is the relationship between VB Projects, Forms, Controls, and so on? The hierarchy can be shown as:
- The Properties of the Control may be set by editing the property list and reset at run time.
- The Methods of the Control are intrinsic routines such as .Show and .Print and those programmed in BASIC code hiding in the control.
- Events are mouse actions (Click, MouseDown, MouseUp) recognized by the control.
The Controls Toolbox
- This is the default list of Controls (Intrinsic).
- Many others may be added using the menu path [Project-->Components-->Controls--> "Microsoft Common Dialog Control 6.0"]
- Every Visual Basic object must have a unique name.
- The default is Command1, Command2, etc.
Suggested Naming Conventions for VB Objects
|Directory list box
|Drive list box
|File list box
|Horizontal scroll bar
|Vertical scroll bar
Naming Conventions for Controls and Forms
- Must begin with a letter
- May contain only letters, numbers and the underscore ( _ )
- Must be no longer than 40 characters
Examples of Controls:
Command buttons are probably the most popular and power controls.
Private Sub cmdChColor_Click()
BackColor = &H1111FF
ForeColor = &HFFFF11
Print "See color change"
- We click the CommandBox tool and drag on Form1 to create Command1
- In Properties of Command1 we edit its Name to cmdChColor
- In Properties we edit its Caption to ChangeColor
- We enter the four Basic statements Beep and change colors
- Running the program and clicking "Change Colors" control produces the output shown
- Note, color code is &HBBGGRR rather than the conventional RRGGBB
VB offers two controls for displaying and/or entering text. These are Text Boxes and Label Controls. Text Boxes are Read/Write; Label Controls are Read Only. Label Controls are useful for labeling controls such as Text Boxes and Scroll Bars which do not have Captions.
Three modes of displaying initial text in Text Boxes include:
- Setting the Text property of the Text Box at design time
- Assigning the Text property in Basic code at run time
- User input at run time
The programmer may control the appearance of Text Boxes at design time by setting properties MultiLine and ScrollBars
- Text Box 1 has Text Property -->"This is some text set..." at design time
- Text Box 2 has MultiLine Property --> True at design time, with input text word wrapping at run time
- Text Box 3 has both MultiLine-->True and ScrollBars --> Both. Word wrap is missing but text can be scrolled.
- No code is required to produce these behaviors.
- There are now 4 labels on this form.
- At the top is the Form Label4 with Caption "ISP Problem Report"
- For Label4 we have modified the properties BackColor, BorderStyle, Caption, and ForeColor.
- For Labels 1-3 we use default values except for ForeColor = Blue
- We changed the BackgroundColor of the 3 TextBoxes to Yellow
- We modified TextBox3 to set MultiLine=True and ScrollBars=Vertical
- Again, no controls contain any code, and labels are read only
- Labels will word wrap if the label box permits
Four controls allow the user to make selections: Check Boxes, Option Buttons, List Boxes, and Combo Boxes. If the GUI application lends itself to selection from discrete items, the programmer should use such controls rather than the more free-form Text Boxes. This strategy minimizes ambiguous and erroneous responses.
- Check boxes allow for mutually inclusive choice.
- That is, check boxes are independent of each other.
- Check boxes toggle.
- Can detect the checkbox click event with subprocedure Sub Check1_Click()
- The property Check1.Value returns 1 if clicked, 0 if not clicked.
For mutually exclusive choice (i.e., 1 "right answer"), we use option buttons.
- This Form contains 1 Label control, 4 Frames, and 18 Option Buttons.
- The Option Buttons are grouped within the 4 color-coded Frames.
- All buttons within each Frame are mutually exclusive.
- All buttons within a Frame are independent of all other buttons.
- Option Buttons may also be grouped within a Picture Box.
- The order of creation is important: Frames or Picture Boxes must be inserted FIRST on the Form, and Options Buttons then inserted into the Frames or Picture boxes.
- Note the use of color-coding to guide the user's eye.
- Note the use of the Frame Caption to label the Option Button group.
Selecting Option Buttons
There are four ways of selecting an Option Button:
1. Clicking it at run time with the mouse.
2. Tabbing to the option button group and then using the arrow keys to select a button within the group.
3. Assigning its Value property in code, e.g.
Option16.Value = True
4. Using the shortcut key specified in the caption of the label.
How do you interpret buttons?
Dim Age As String, Marital As String
Dim NChildren As String, Income As String
Private Sub Option1_Click()
MsgBox "Age = Under 20"
Private Sub Option11_Click()
NChildren = ", have Two children "
Private Sub Option16_Click()
Income = ", and earn between
$50K and $75K a year."
lblPersonal.Caption = "You are "
& Age & Marital & NChildren & Income
Private Sub Option3_Click()
Age = "30 - 40 years old"
Private Sub Option7_Click()
Marital = ", Married "
- We declare 4 variables, Age, Marital, NChildren, and Income as Strings
- Each Option Button has a Sub OptionN_Click() which assigns appropriate string values to these variables
- The Option_Click subprocedures in the last frame reports the results of the survey by resetting the Label caption, lblPersonal.Caption
Using List Controls
List Controls allow the user to select items from alphanumeric lists. The two intrinsic list controls are:
List boxes allow the user to select one (or more) items from a list. The MultiSelect property determines the selection mode:
- MultiSelect = 0 --> Select only one item at a time (default)
- MultiSelect = 1 --> Simple multiselect, all items clicked are selected
- MultiSelect = 2 --> Extended multiselect, using <Shft>+<Ctrl> = Range or <Ctrl> = Mode 1
Private Sub Form_Load()
- We add items to List 1 with List1.AddItems in Form1
- Items can be removed by inserting in the Sub List1_Click()
Combo boxes combine the features of a text box and a list box. Thus, the user can select one of the choices from the list or enter a novel item in the text box.
Public Message As String
Private Sub Combo1_Change()
Message = Combo1.Text
Private Sub Form_Load()
- The Combo Box opens with Combo1 in editable text window
- We change that to "Puerto Rico"
- Every letter of the change is registered in the global variable Message
- We click the "Print New Entry" Command Box to view current contents
Picture Boxes serve at least three distinct functions:
To display a picture or image
To serve as a container for other controls (like a Frame)
To serve as a canvas for graphical objects and animations
Forms themselves actually have a Picture property which can be used as a backdrop image on the form. Image file formats include:
- Bitmap [*.BMP]
- Windows Metafile [*.wmf]
- Graphics Interchange Format [*.GIF]
- JPEG [*.JPG]
- Icon [*.ICO]
- Both images are taken with an Olympus 400Z digital camera and reduced to 25%
- The left-hand image is imported directly on the Form
- The right-hand image is in a Picture Box
- The distortion in the labels is due to saving the files as .JPG (image compression)
Image Controls are called "Lightweight Graphical Controls" because they support only a subset of the properties, methods, and events of Picture Boxes. However, for that reason they load faster and require less system resources than Picture Boxes.
- These Image Control graphics were imported from Visual Studio's -->Common-->Graphics-->Metafile
- They could just have well been bitmaps as in Example 2.10.
- Image Controls cannot serve as containers for other VB controls
Lines and Shapes
Visual Basic provides standard OOP drawing tools for designing and enhancing graphics.
- Shapes and lines may be drawn on forms, but only lines on Picture Boxes
- Shapes include Rectangle, Square, Oval, Circle, Rounded Rectangle, Rounded Square
- Shapes support an impressive list of properties of color, style, and drawing mode
- Shapes and lines are real "objects" and may be modified during the design
- Shapes and lines do NOT support events; they are decorative only
- Standard graphics drawing tools and features missing in VB include:
- Group & Ungroup
Menus and Dialogs
Menus and Dialog Boxes provide powerful and abstract tools for GUI communication. Visual Basic has an easy-to-use Menu Editor and an array of Dialog Boxes.
Let's look at the Menu Editor. It's under the Tools menu.
- The Menu Editor rapidly and easily build standard menus
- Menus are very efficient GUI objects for grouping and organizing methods
- The tools are very abstract and powerful
- The menu items, as created, are "empty", that is, you still need to add code
Dialog boxes are convenient devices for doing I/O in a GUI. Consider the following simple example:
Private Sub Command1_Click()
Dim lngSSN As Long
lngSSN = InputBox("Please enter
your Social Security Number")
MsgBox "The SS # is " & lngSSN
- Input is by the function InputBox
- Output is by the function MsgBox
- This mode of input does have problems - type checking, for instance.