Seminar 2

Visual Basic GUI -

Controls, Events, and Interaction

© Morris Firebaugh



Topics:



OOP Concepts

Recall the two characteristics of the Visual Basic language:

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.


Background


Graphical Summary of OOP Concept


Objects in Visual Basic

The following are examples of the types of objects available in Visual Basic.

Example

Description

Command button

Controls on a form, such as a command buttons and frames, are objects.

Form

Each form in a Visual Basic project is a separate object.

Database

Databases are objects, and contain other objects, like fields and indexes.

Chart

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).

Example 2.1

Two Visual Basic Objects:

a Form (called Form1)

a CommandButton (called Launch)

See:

  1. Two objects are shown on the left, and one (CommandButton) is selected
  2. 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.

  1. 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"?
  2. 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.
  3. Transparency – The goal of an effective GUI/application program is to make the computer "invisible" and to focus the user’s 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 let’s see, how do I perform the next step?", the GUI/application program has failed the transparency principle.
  4. 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.
  5. 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.
  6. 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, I’m 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.
  7. 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:


VB Object Hierarchy

What is the relationship between VB Projects, Forms, Controls, and so on? The hierarchy can be shown as:

Note:

  1. The Properties of the Control may be set by editing the property list and reset at run time.
  2. The Methods of the Control are intrinsic routines such as .Show and .Print and those programmed in BASIC code hiding in the control.
  3. Events are mouse actions (Click, MouseDown, MouseUp) recognized by the control.


The Controls Toolbox

Note:

  1. This is the default list of Controls (Intrinsic).
  2. Many others may be added using the menu path [Project-->Components-->Controls--> "Microsoft Common Dialog Control 6.0"]
  3. Every Visual Basic object must have a unique name.
  4. The default is Command1, Command2, etc.

Suggested Naming Conventions for VB Objects

Object

Suggested Prefix

Example

Check Box chk chkFreshman
Combo Box cbo cboState
Command button cmd cmdBackgroundColor
Data dat datDriveSales
Directory list box dir dirEmployees
Drive list box drv drvZip
File list box fil filDocuments
Form frm frm1040Tax
Frame fra fraProgramSelection
Horizontal scroll bar hsb hsbTemperature
Image img imgCompanyPicnic
Label lbl lblVelocity
Line lin linArrow
List box lst lstBoardDirectors
Menu mnu mnuBeverages
Picture box pic picFamilyAlbum
Radio button opt optStation
Shape shp shpOrgChart
TextBox txt txtInstructions
Vertical scroll bar vsb vsbBudget

Naming Conventions for Controls and Forms



Examples of Controls:

Command Button

Command buttons are probably the most popular and power controls.

Example 2.1

Private Sub cmdChColor_Click()
    Beep
    BackColor = &H1111FF
    ForeColor = &HFFFF11
    Print "See color change"
End Sub

See:

  1. We click the CommandBox tool and drag on Form1 to create Command1
  2. In Properties of Command1 we edit its Name to cmdChColor
  3. In Properties we edit its Caption to ChangeColor
  4. We enter the four Basic statements Beep and change colors
  5. Running the program and clicking "Change Colors" control produces the output shown
  6. Note, color code is &HBBGGRR rather than the conventional RRGGBB


Text Boxes

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:

  1. Setting the Text property of the Text Box at design time
  2. Assigning the Text property in Basic code at run time
  3. User input at run time

The programmer may control the appearance of Text Boxes at design time by setting properties MultiLine and ScrollBars

Example 2.2

See:

  1. Text Box 1 has Text Property -->"This is some text set..." at design time
  2. Text Box 2 has MultiLine Property --> True at design time, with input text word wrapping at run time
  3. Text Box 3 has both MultiLine-->True and ScrollBars --> Both. Word wrap is missing but text can be scrolled.
  4. No code is required to produce these behaviors.


Label Control

Example 2.3

See:

  1. There are now 4 labels on this form.
  2. At the top is the Form Label4 with Caption "ISP Problem Report"
  3. For Label4 we have modified the properties BackColor, BorderStyle, Caption, and ForeColor.
  4. For Labels 1-3 we use default values except for ForeColor = Blue
  5. We changed the BackgroundColor of the 3 TextBoxes to Yellow
  6. We modified TextBox3 to set MultiLine=True and ScrollBars=Vertical
  7. Again, no controls contain any code, and labels are read only
  8. Labels will word wrap if the label box permits


Check Boxes

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.

Example 2.4

See:

  1. Check boxes allow for mutually inclusive choice.
  2. That is, check boxes are independent of each other.
  3. Check boxes toggle.
  4. Can detect the checkbox click event with subprocedure Sub Check1_Click()
  5. The property Check1.Value returns 1 if clicked, 0 if not clicked.


Option Buttons

For mutually exclusive choice (i.e., 1 "right answer"), we use option buttons.

Example 2.5

See:

  1. This Form contains 1 Label control, 4 Frames, and 18 Option Buttons.
  2. The Option Buttons are grouped within the 4 color-coded Frames.
  3. All buttons within each Frame are mutually exclusive.
  4. All buttons within a Frame are independent of all other buttons.
  5. Option Buttons may also be grouped within a Picture Box.
  6. 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.
  7. Note the use of color-coding to guide the user's eye.
  8. 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:

How do you interpret buttons?

Example 2.6

Option Explicit
Dim Age As String, Marital As String
Dim NChildren As String, Income As String


Private Sub Option1_Click() MsgBox "Age = Under 20" End Sub
Private Sub Option11_Click() NChildren = ", have Two children " End Sub
Private Sub Option16_Click() Income = ", and earn between $50K and $75K a year." lblPersonal.Caption = "You are " & Age & Marital & NChildren & Income End Sub
Private Sub Option3_Click() Age = "30 - 40 years old" End Sub
Private Sub Option7_Click() Marital = ", Married " End Sub

See:

  1. We declare 4 variables, Age, Marital, NChildren, and Income as Strings
  2. Each Option Button has a Sub OptionN_Click() which assigns appropriate string values to these variables
  3. 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 Box

List boxes allow the user to select one (or more) items from a list. The MultiSelect property determines the selection mode:

Example 2.7

Option Explicit


Private Sub Form_Load() List1.AddItem "AL" List1.AddItem "AK" List1.AddItem "AZ" List1.AddItem "AR" List1.AddItem "CA" List1.AddItem "CO" List1.AddItem "CT" List1.AddItem "DE" List1.AddItem "FL" List1.AddItem "GA" List1.AddItem "HI" List1.AddItem "ID" List1.AddItem "IL" List1.AddItem "IN" List1.AddItem "IA" List1.AddItem "WI" List1.AddItem "WY" End Sub

See:

  1. We add items to List 1 with List1.AddItems in Form1
  2. Items can be removed by inserting in the Sub List1_Click()
List1.RemoveItem   List1.ListIndex


Combo Box

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.

Example 2.8

Option Explicit
Public Message As String


Private Sub Combo1_Change() Message = Combo1.Text End Sub
Sub Command1_Click() MsgBox Message End Sub Private Sub Form_Load() Combo1.AddItem "AL" Combo1.AddItem "AK" Combo1.AddItem "AZ" Combo1.AddItem "AR" Combo1.AddItem "CA" Combo1.AddItem "CO" Combo1.AddItem "CT" Combo1.AddItem "DE" Combo1.AddItem "FL" Combo1.AddItem "GA" Combo1.AddItem "HI" Combo1.AddItem "ID" Combo1.AddItem "IL" Combo1.AddItem "IN" Combo1.AddItem "IA" Combo1.AddItem "WI" Combo1.AddItem "WY" End Sub

See:

  1. The Combo Box opens with Combo1 in editable text window
  2. We change that to "Puerto Rico"
  3. Every letter of the change is registered in the global variable Message
  4. We click the "Print New Entry" Command Box to view current contents


Graphics


Picture Boxes

Picture Boxes serve at least three distinct functions:

  1. To display a picture or image

  2. To serve as a container for other controls (like a Frame)

  3. 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:

Example 2.9

See:

  1. Both images are taken with an Olympus 400Z digital camera and reduced to 25%
  2. The left-hand image is imported directly on the Form
  3. The right-hand image is in a Picture Box
  4. The distortion in the labels is due to saving the files as .JPG (image compression)


Image Controls

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.

Example 2.10

See:

  1. These Image Control graphics were imported from Visual Studio's -->Common-->Graphics-->Metafile
  2. They could just have well been bitmaps as in Example 2.10.
  3. 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.

Example 2.11

See:

  1. Shapes and lines may be drawn on forms, but only lines on Picture Boxes
  2. Shapes include Rectangle, Square, Oval, Circle, Rounded Rectangle, Rounded Square
  3. Shapes support an impressive list of properties of color, style, and drawing mode
  4. Shapes and lines are real "objects" and may be modified during the design
  5. Shapes and lines do NOT support events; they are decorative only
  6. Standard graphics drawing tools and features missing in VB include:


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.

Example 2.12

See:

  1. The Menu Editor rapidly and easily build standard menus
  2. Menus are very efficient GUI objects for grouping and organizing methods
  3. The tools are very abstract and powerful
  4. The menu items, as created, are "empty", that is, you still need to add code


Dialog Boxes

Dialog boxes are convenient devices for doing I/O in a GUI. Consider the following simple example:

Example 2.13

Option Explicit



Private Sub Command1_Click() Dim lngSSN As Long lngSSN = InputBox("Please enter your Social Security Number") MsgBox "The SS # is " & lngSSN End Sub

See:

  1. Input is by the function InputBox
  2. Output is by the function MsgBox
  3. This mode of input does have problems - type checking, for instance.