Hour 3


During this hour you will learn

Adding Controls to a Program

This lesson is one of the most important hours in your Visual Basic tutorial. In this lesson you'll create a new project and add a new form to that project. The form will contain controls that interact with the user (the user is you, in this case) who runs your application. You'll create this application without the help of the Visual Basic application wizard. By creating the application from scratch, you'll learn important Visual Basic fundamentals that you'll use almost every time you work with Visual Basic.

The user interface is vital to your Windows programs, because the programs visually interact with users. In the text-based programs of old, programmers had to write tedious code every time they wanted to display information for users or request information from the user. Visual Basic virtually eliminates all coding for I/O (input/output). Visual Basic takes care of the tedious details so that you can concentrate on your program's more important and application-specific details.

Topic 1: Creating New Applications

Without the VB Application Wizard, you need to control more of your application's creation details. For example, you'll size the Form window, add controls to the form, add possible extra forms, and specify the behavior of the application.

FAST TRACK
Have you used a previous version of Visual Basic to add controls to forms? If so, you'll want to skip to the third topic, "Setting Property Values", to see how Visual Basic 5 improves the control process.

Overview

Visual Basic creates empty projects that contain only one form when you create new applications from scratch. After you learn to create these initial projects, you'll need to add the details to the form so that your application does the work you need done.

The New Application Project

As you already know, a Visual Basic application contains at least one form and possibly several other files, such as extra forms, modules, and resources. Therefore, when you want to create a Visual Basic application, you'll need to create a new project. New projects are blank slates that you can change and build on as you create your final application.


Don't start a new application until you have a good idea what you want the application to do. Sketch the forms that the user will see, get a good idea of the data you want to produce, and design the output (such as reports) that you want the application to generate. Although Visual Basic offers a flexible programming environment that lets you change your mind after you begin building a new application (unlike former programming tools that made modification more difficult than it was worth), you should have a good idea where your application is headed before going to the keyboard to begin your project.

Creating the New Application

Follow these steps to start a new application:

  1. If you've just started Visual Basic, double-click the Standard EXE icon to tell Visual Basic that you want to create a standard Windows program. If Visual Basic is already running, from theFile menu choose New Project; then select Standard EXE from the dialog box that appears. Visual Basic creates a new project.
  2. Your screen should look similar to Figure 3.1. As you can see from the Project window (which displays all the application's components), the new project now holds only a single form, Form1.

Figure 3.1

Visual Basic just created a new project.

Size coordinates, Form-location coordinates

  1. In the Form window, drag the lower-right resizing handle down and to the right to expand the size of your application's form. Coordinate positions on the right side of the toolbar describe the width and height of the application's form. The coordinates appear in a twip measurement (a twip is one screen dot). Size your form so that it measures approximately 7,400 by 5,200 twips. This first application's form won't take much of the screen, so the resulting application will appear in a small window.

The toolbar not only shows the form's coordinate sizes, but also the placement of the form on the end user's screen. The default form location is 0,0, which means that the form will appear in the upper-left corner of the screen when you or someone else executes the application. The first coordinate measures the number of twips from the left of the screen; the second measures how far from the top of the screen the form's upper-left corner appears. Although you can change the location of the form by specifying properties as described in this hour's last topic, you'll probably move the form's screen placement with the mouse from the Form Layout window. For this lesson, don't change the form's location.

Standard Naming Prefix Conventions

One of the most important and useful tasks you can perform when you see a new application element is to name that element. The default name that Visual Basic supplies is usually a bad one. For example, the name Form1 is a lousy name for a form. If you were to add nine more forms and followed Visual Basic's naming conventions, your project would contains forms named Form1, Form2, and so on. By changing the default name to a more descriptive one, you'll better remember the purpose of the form later when you must work with multiple form lists.

Visual Basic programmers often use a naming prefix before such Visual Basic components as forms and controls. The prefix tells you what the component is. Therefore, you can distinguish between a form and a label control when you name the components frmDataEntry and lblSaleCode, whereas the underlying component type isn't obvious without the prefixes.

Table 3.1 contains a list of the common Visual Basic naming prefixes. When you assign a name to a Visual Basic element, use the prefix to clarify the underlying element's nature.

Table 3.1 Common Visual Basic Naming Prefixes

Prefix

Element Named

cbo Combo box

chk Check box

cmd Command button

dir Directory list box

drv Drive list box

fil File list box

fra Frame

frm Form

grd Grid

hsb Horizontal scroll bar

img Image

lbl Label

lin Line

lst List box

mnu Menu

mod Module

ole OLE

opt Option button

pic Picture box

res Resource

shp Shape

tmr Timer

txt Text box

typ User-defined data type

vsb Vertical scroll bar

Example

Study the callouts in Figure 3.2. Notice that the form's title bar contains the form name (Form1) and that the name also appears in the Project window. The Properties window also describes the form, as you can see from the name at the top of the Properties window. You should be getting familiar with how projects and their components go together to form a Windows application.

Figure 3.2

The project names and property locations.

Form name, Project name, Project file name, Form name, Form file name, Form name


Don't give a prefix to file names. The file name extension describes the file type. For example, the .frm extension tells you that the file is a form file. Visual Basic uses the .vbp extension for Visual Basic project file-name extensions. Rarely will you need to work with individual Visual Basic files outside the Visual Basic environment, but you should understand the file-name extensions so that you'll be able to recognize what the file is for when looking through a directory of Visual Basic files.

Although you won't begin working with the Properties window until Hour 4's lesson, you can use the Properties window to change the name of your form now for practice. Notice the top entry in the Properties window named (Name). (If you don't see the entry, scroll the Properties window to the top.) The current name is Form1, but you can change the name to frmMyFirst by clicking the (Name) entry and typing the new name.


The Properties window describes all your application's components, including controls and forms, so the description to the right of each name helps you verify the Properties window's item now being shown.

After you type the new name, notice that the Project window now reflects the form's new name (as does the Properties window text box).

The default file name that Visual Basic gives to all forms is the Visual Basic form name with the .frm extension. Therefore, when you eventually save the form to disk, Visual Basic will add .frm to the form's file name for you.

Next Step

Before adding more to your new application, save the project to your disk-from the File menu choose Save ProjectName. The Save ProjectName command saves, in one step, your entire project and all the items in the Project window. (Before saving your project files, be sure to select an appropriate directory.) The Save ProjectName command first saves your forms (if you've yet to save them before now) and then the project itself.

Save ProjectName asks for a form name and a folder. The command uses the new form name you added in the previous section but uses Project1.vbp for the project name, which, as you might guess, is a bad name. Change the project's name to MyFirst before clicking OK to carry out the save (you don't need to type the .vbp extension; Visual Basic adds the extension for you). Visual Basic places the project's new name on VB's title bar at the top of your screen as soon as you name and save the project.

Now that you've saved the initial project, you can save later by using the Save ProjectName command, and Visual Basic won't prompt you again for the name.


If you make extensive changes to a form and want to save the form but not the rest of the project, choose Save ProjectName from the File menu (Visual Basic replaces ProjectName with your current project's name on the File menu's Save ProjectName option).

Topic 2: Adding Controls to the Application

The new form is rather dull looking, but you'll change that in a hurry. This topic section explains how to add controls to your new form. Although the controls will arrive on your form in their generic format, you'll learn how to place and size them in this topic section, and then how to specialize the controls in the next topic section so that they look the way you want them to look.

Overview

Visual Basic offers several ways to place controls on your form. Generally, you'll double-click or drag a Toolbox control to your form. After you place a new control on the form, you then can size and move the control where you want it. Keep in mind that you'll place controls on your form during the design of your application. The controls won't behave as they will when the user eventually runs the program, but you'll see what the controls look like from within the development environment.

The Toolbox generates controls for your Form window. When you place a control on the form, that control comes from the Toolbox. The Toolbox holds an unlimited number of controls; you can get as many labels, text boxes, and other controls from the Toolbox as you need for your form. If you add additional forms to your application, the Toolbox supplies controls for those forms as well.

To place a control on the form, you can do one of two things:

After you place a control on the form, you'll want to modify the control so that it behaves the way you expect.

Example

In this example, you create a simple application from scratch that you'll complete in Hour 4's lesson. Your first from-scratch application won't be fancy, but you'll learn Visual Basic fundamentals that you'll use every time you write subsequent applications. This application's Form window will contain the following controls:

You'll start with the blank form you created in the previous topic section. Follow these steps to add controls to the form:

  1. Double-click the Label control. Visual Basic puts a new label in the center of your Form window. Move the control higher on the form to the approximate position in Figure 3.3.

Figure 3.3

You've placed and moved your first control.

  1. The control doesn't look like much, does it? You'll rectify that after adding other controls, as described next.
  2. Double-click the Command Button control to place a command button in the middle of your Form window. Leave the command button where it appears for now.
  3. Click once on the Image control. Move your mouse to the Form window. The mouse pointer appears as a plus sign to show that you've selected a control.
  4. Drag your mouse to outline the new Image control on the Form window. Figure 3.4 shows where you should place the control. Try to get close to the figure's placement and size.

Figure 3.4

The third control is now placed at the bottom of the Form window.

  1. As you can see from the measurements, Figure 3.4's Image control measures 2,175 twips wide and 1,825 down. The control starts (in the upper-left corner) at twip measure 2,520 (the number of twips from the left of the form) and 2,880 (the number of twips from the form's top edge). As long as you come close to these measurements, you'll have placed the control where it goes.
  2. The Image control will hold a graphic image, but not until you specify the image's file name that will appear in the Image control's property.
  3. Open the Form Layout window by selecting Form Layout Window from the View menu. You can see from the Form Layout window that your form will appear in the upper-left corner of the user's window at runtime.
  4. Center the Form Layout window's form image on-screen by dragging the image with your mouse. You won't see the form itself move yet because you're not moving the form on Visual Basic's development environment screen with the Form Layout window; rather, you're specifying the location where you want Visual Basic to display your form at runtime.

This would be a good time to save your project (choose Save ProjectName from the File menu). You've already named and saved everything before, so Visual Basic won't prompt you for form and project file names this time.


If you were to exit Visual Basic without saving your project, Visual Basic would warn you that you haven't saved and give you one more chance to save your work. Never turn off your computer while working with an open Visual Basic project. Always exit Visual Basic to make sure that you've saved all your recent changes. Actually, you should be in the habit of shutting down Windows properly before powering off your computer so that Windows can safely store settings and close files correctly.

Next Step

You've now added three controls to your form. The Form window may not look like much of an application, but you're close to making the controls look much better in the next topic section. Before sprucing up the controls and your application, this might be a good time to run your new application. That's right-even though you haven't done much, you have created a working application.

When you click the Start button, Visual Basic checks your application for errors, generates runtime codes, and runs your program. Figure 3.5 shows the result. Visual Basic still resides in the background, but you could run your program outside Visual Basic if you first compiled the code (which you won't do until Hour 6's lesson).

Figure 3.5

You've created a running application.

Although the control text isn't centered and you can't even see the Image control, you've learned the most important part of Visual Basic programming-placing controls. Much of a Visual Basic programmer's job takes place by managing controls on the Form window.

Perhaps you're beginning to see why the controls are your program's path to the outside world. The user will use the controls to read your program's output and respond with program input. Therefore, you've created a working application with a full user interface without writing one line of Visual Basic code. Of course, the application won't do much until you put code behind the controls and write code that can tie the application's tasks together, but you've built much of the user interface already.


Don't worry, your Image control does appear on your Form window-you just can't see it. An image's default state is to show nothing and display no borders. You'll change the image's properties in the next topic so that the Image control displays a picture when you run the program.

The Picture Box control works a lot like the Image control. You placed the Image control in this lesson's application because the Image control is much more efficient than the Picture Box control. The Image control responds more quickly by displaying its image faster than the Picture Box. Hour 19's lesson describes the Picture Box and explains how the Picture Box varies from the Image control.

Click the command button a few times. See what happens? Visual Basic added all the code necessary to show the command button pushing in when you click it. You're triggering a Windows event as a result. The application does nothing to respond to that event, however, because no event code appears behind the command button. You'll add some code in Hour 4's lesson. For now, close your program by clicking the Close window button.


The grid of dots that appears on your application's form at design time doesn't appear at runtime. This grid lets you align controls with each other. You can hide the grid or change the grid dot spacing by choosing the General page of the Options dialog box that you can display by choosing Options from the Tools menu. The Options General dialog box contains the Align Controls to Grid option, which forces your form controls to move to the nearest grid dot when you place controls on your form. If you deselect this option, the grid can still appear as a guide, but you can place controls between grid dots.

Topic 3: Setting Property Values

Properties, or property values, determine how controls are unique to one another. Without changeable properties, every command button would be the same size and color, contain the same caption, and be indistinguishable from any other command button on your form. Most of the controls support these common properties:

This topic section explores some of these more common control properties and ends by letting you modify your application to make the form's controls look better. Figure 3.6 shows a form with eight command buttons. All the command buttons work the same-that is, when you click a command button, you trigger a command button event that causes each button to look pushed in. As you can see, however, the different properties of the eight command buttons make them look completely different from each other.

Figure 3.6

Command button properties distinguish controls from one another.

Overview

You're used to working with properties in everyday life. Some people are thin, some are fat, some honest, some dishonest, some law-abiding, some law-breaking, some nice, some mean, and so on. Each description is a property that you can attribute to some people. The properties that you set for controls gives each control a "personality" and look, just as character traits give each person a different personality and look.

You can set some properties at design time, some at runtime, and some at both times. When you want to change the appearance or behavior of a control during the program's execution, your Visual Basic code will change that control's properties. If a control doesn't change during a program's execution, you'll set that control's properties when you write your program (at design time). If certain properties-such as items in a list box control-aren't available at design time, you'll have to set those properties at runtime with code.

Design Time vs. Runtime

Visual Basic programming requires a special thinking mode. You need to distinguish between runtime events and design-time requirements. You write and modify your application t design time. You run the application at runtime. Often, Visual Basic newcomers confuse terms such as events and properties. The job becomes more confusing when you learn about Visual Basic methods and modules. Keep in mind that an event occurs when you or someone else runs your program and performs some action, such as click a command button. A property is a descriptive fact about a control, such as the control's size or color.

The Properties Window

You'll see each control's property in the Properties window. The Properties window changes to display every design-time property available for a control when you select the control. For example, if you select your application's command button, the Properties window displays properties unique to command buttons and lets you set specific values for the selected command button. If you then select the label, the Properties window updates to show you the label properties now set.

Visual Basic automatically assigns default values to each control when you place the control on your form. For example, Visual Basic assigns the first command button the Caption property Command1. That's why you see the Command1 caption on the control that you placed on your application's form.

Many of the default values work fine, but you'll almost always change some of the values. For example, the Top and Left properties indicate where the control appears on your form. If you drag the control to a different location, Visual Basic automatically updates these location properties for you. Rather than drag the control, you could enter their twip locations directly in the Properties window, and Visual Basic moves the controls to the specified location as soon as you enter the property value.


You don't have to select a control to work with that control's properties. Rather than click a control, you can select a control from the Properties window's drop-down list box. Figure 3.7 shows the Properties window's control-selection drop-down list box.

Figure 3.7

Select the control whose properties you want to modify.

The control's drop-down list box

Notice that Visual Basic displays a description of the selected property at the bottom of the Properties window. Therefore, you don't have to display help if you forget what a property specifies. Also, if you click the Properties window's Categorized tab, you see the selected control's properties organized by such categories as appearance and screen position. By collapsing categories you don't want to see, you can hide the properties you're not interested in at the moment.

Form Properties

Controls aren't the only Visual Basic items with properties. Notice that Figure 3.7's Properties window drop-down list includes the form as well. Forms have properties.

Think about how one form might vary from another. One form might be blue, whereas another is red. A form's title bar could hold a title that describes the form's contents. The form might support the use of a control menu and icon, or no control menu. A form's window might be resizable, or you may not want to give the user the ability to resize the form's window.

You're rarely finished with an application until you specify the form's properties. If you look at the sample application from the previous two topic sections, notice that the form's title bar shows Form1, even though you've assigned the name frmMyFirst to the form. The form's title-called a caption in Visual Basic terminology-is a control property you'll change before you complete this hour's lesson.

Example

It's now time to add properties to the controls on your application's form. Before you complete this hour's lesson, you'll have completely improved the appearance of your application. The application still won't do anything (other than let you click the command button), but the application will contain a proper form caption and control properties.

Follow these steps to modify your application's control properties:

  1. Click the control named Label1 to display the label's properties in the Properties window.
  2. Click the Properties window's Caption entry.
  3. Type Have a happy day! As you type, you'll see the label's caption change.
  4. Click the Properties window's Font entry. A font name doesn't appear, but a set of ellipsis does. Ellipsis after a property value always indicates that you can select from a list of choices rather than type the value directly into the Properties window.
  5. Click the Font entry's ellipsis to display the Font dialog box. A font supports multiple properties, so you must use the dialog box to specify the font name, size, and style.
  6. Select the Courier New font, with a Bold style and a 36-point size.
  7. Close the Font dialog box. Resize the label's caption to see more of it. Although you can drag the label's edges, you'll instead enter location and size values directly in the Properties window so that your application matches the one in this book.
  8. Set these Properties window values: Left, 1,320; Height, 1,695; Top, 120; and Width, 4,695. You can now read the new label's caption, but the caption is still left-justified. Expand the Properties window's width if you need more room to read the property values.
  9. Click the label's Alignment property. Click the drop-down list box arrow to open the list box and you'll find three values: Left Align, Right Justify, and Center Justify. Select Center Justify, and the label straightens up nicely.

Notice that Visual Basic displays numbers to the left of each property. You could type a number to select the number's corresponding alignment style. Also, you'll use the numbers inside Visual Basic code to set property values without having to type the entire description, such as Right Justify.

At this point, your screen should look something like the one in Figure 3.8.

Figure 3.8

The label now contains a nice caption.

  1. Select the form's command button, click the Caption property, and then type Click Here for the caption.
  2. Save your project. You're not going to do anything with the image until Hour 4's lesson, when you'll add some code to surprise the user with a pop-up image.

As you learn Visual Basic, you'll also learn about several literals (sometimes called named literals or named constants) that correspond to property values. For example, Visual Basic recognizes a constant named vbLeftJustify that corresponds to the Alignment's Left Justify property value. In addition to assigning 0 to the property when you want to change a control's alignment to left-justified through code, you can assign vbLeftJustify to the control. When maintaining the program later, you'll recognize what vbLeftJustify means faster than you would remember what 0 stands for, even though both mean the same in this control's Alignment property. Your night-school tutorial will keep you posted on the best use of the named constants when you begin programming.

Next Step

As your applications become more complicated, you'll learn ways to make the program creation run smoothly. As your applications become more powerful, you'll use Visual Basic code to access controls and properties. To make that access more manageable, you should assign names to your controls. Although Visual Basic assigns default names, such as Command1 and Label1, you should assign names that use the naming prefix followed by a description of the control. For example, you could change your application's label name (specified by the (Name) property at the top of the Properties window) from Label1 to lblHappyApp. Change the command button name from Command1 to cmdGetHappy (you'll see why that name is good in Hour 4's lesson). Although the Image control still is invisible, go ahead and change its name to imgViewHappy.

Taking the time to change control names might seem a waste of time at this point, but the names pay dividends later as you add to your programs. In Hour 4's lesson, you'll add Visual Basic event code to your controls, and your code will be clearer if you rename your controls now. You'll have no ambiguity, especially if you later decide to add additional command buttons and labels to your project.

In addition to the controls, you should modify the form's properties. The only property that really needs changing is the form's caption; change it to Happy Face. Also, select False for the MaxButton property, so the user won't be able to maximize the application's window to full screen and the controls will stay centered on the form.

When you run your application, you'll see the application's window appear like the one in Figure 3.9. The window's maximize button is grayed out, so the user can only minimize the window.

Figure 3.9

Your application's window is looking better.

Save your project so you can continue adding functionality to it in Hour 4's lesson.


Unlike this lesson's example, you won't always add all your form's controls before setting their properties. Usually, you'll add a control and set many or all of its property values before adding additional controls. After you add several controls to a form and see how they look together, you may need to change additional properties, such as their sizes and locations.

Summary

You can now place controls on your form and modify the control properties. The user interface is vital to an effective end-user application. Fortunately, Visual Basic takes care of the tedious details and handles the user interaction; your job is to place those controls and make them look and behave the way you want them to look and behave.

How are you supposed to know every property that exists for every kind of control? Actually, very few Visual Basic programmers know all the control properties because there are too many properties to remember, and you rarely change many of them. The Visual Basic online help system displays a list of properties if you click Properties on any help screen that describes a control. You'll see more controls than you'll see in the Properties window because of the controls that you can modify only at runtime with code.

In Hour 4 you'll learn how to teach your application to respond to events. At the end of the lesson, your application will be complete, and your program will directly respond with the user at the keyboard.

Hour 3 Quiz

  1. What's the default name that Visual Basic assigns to a new project's form?
  2. Why do you not use prefixes for Visual Basic component file names?
  3. What file-name extension does Visual Basic use for project files?
  4. True or false: Visual Basic Property values describe the costs of owning real estate.
  5. Why does the form have properties?
  6. What's the name of the command button title's property?
  7. True or false: You can't change some properties at design time.
  8. Why do some property values have ellipses after their Properties window entry?
  9. Why should you change the control names from their default values?
  10. How can you keep the user from using your application window's maximize button?

Hour 3 Homework Exercises

  1. Save this lesson's project under a new name, perhaps Homework3, so that this exercise won't change the book's application. Modify the new project as follows: Change the command button's Background color property to blue. Run the application to see what happens. The result might surprise you because the command button won't be blue! Some properties, such as command button colors, require that you set additional properties. Change the command button's Style property to Graphical; the command button turns blue when you run the application.
  2. Create a new project and add two command buttons to the form. Make the buttons look differently by using a different font and color on each. Add a label between the two buttons that reads A button above and below. Name your controls and change the form title to My 2nd Application. Although this exercise is simple, you'll be reviewing this hour's lesson well if you create this application.


© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.