vel404






Visual Basic 4 in 12 Easy Lessons vel404.htm













Visual Basic 4 in 12 Easy Lessons vel404.htm






















What You'll Learn



Event-Driven Environments



Control Properties



Naming Conventions



More Consistency: Named Constants



Quick to the Draw!



Homework





General Knowledge



Find the Bug



Extra Credit









Unit 4









Bare-Bones Programs











What You'll Learn





Event-driven environments





Control properties





Naming conventions





Why named constants improve program maintenance







In this unit, you will create your own program with Visual Basic from scratch. You will write a fully working Windows program that displays a resizable window, a command button, and a control button with a control button menu.



Before you create your first application, however, you must understand how Visual Basic programs interact with the Windows environment.











Event-Driven Environments











Concept: A Windows program behaves differently from a DOS-based program. Instead of the program controlling the user, the user controls the program. When the user responds to a menu or control, Windows generates an event that describes the particular action.

Picture yourself driving down the road. All kinds of controls are at your fingertips—steering wheel, blinkers, headlights, breaks, gas pedal, gear shift, radio knobs, rearview mirror, air conditioning, and heater controls. At any time, you might press the brake, turn left, turn on the radio, adjust the mirror, or speed up. The driving conditions, not the physical order of the controls, determine what you do next.

When you press the gas pedal, does your foot alone make the car go faster? The answer is no. You would have to have a very powerful foot to be able to speed up a car already going 50 miles per hour. The foot pedal causes an event to happen. That event is that more gas is fed to the car for fuel to burn and the car goes faster. Your car performs its job and makes adjustments based on the events that you trigger.















Definition—An event can be a mouse move, a mouse click, a keystroke, or a control response, as well as a score of other possible Window operations.







Using a Windows program is like driving a car in the following respect: You do not always perform the same actions, and the actions that you perform cause certain events to occur. In Windows terminology, an event is the action that the user takes. Whenever the user clicks the mouse, presses a key, responds to a control, or selects from a menu, an event happens. Windows constantly monitors the running Visual Basic program, looking for events.











Note: Too many things can happen in a GUI-based program for it to follow a straight, sequential pattern. If you were to run a DOS-based accounting program, the program more than likely would present you with a menu of limited choices. Only after you select from the menu, does the program take you through the next step. In a Windows program, you are offered a selection of controls, and you can respond to any control in any order. The program must be able to sense when an event takes place and to handle it accordingly.







Windows and Visual Basic constantly monitor running programs. When the user clicks a command button or performs any other kind of event, Windows intercepts the event and sends it to Visual Basic.



Visual Basic does not respond to some special system events, such as when the user presses Alt+Tab to switch to another application running in memory. That is why Windows must interpret all events and pass the ones handled by Visual Basic to Visual Basic. Figure 4.1 shows the relationship between events and event procedures. Notice that Windows always intercepts the events and passes the appropriate events to the Visual Basic program, where Visual Basic then does something in response to them if event procedures are available.



Figure 4.1. Windows intercepts events before it passes them to Visual Basic.











Definition—An event procedure responds to an event.







When Visual Basic gets an event from Windows, it checks whether the programmer wrote an event procedure for the event. If an event procedure exists, Visual Basic executes the event. In the CONTROLS.VBP program that you ran in the previous unit, clicking the Next Control command button caused the next control in the program's repertoire of controls to appear. The only way that the program could respond to the Next Control command button was for an event procedure to be written for that particular event—namely, the command button keypress.



A program can contain controls and still not respond to all events. In CONTROLS.VBP, for example, when you select the check boxes, nothing happens except that the boxes are selected or deselected. The check box controls handle the checking and unchecking of the boxes so that no event procedure is needed to do that. Once you select check boxes, though, the program does absolutely nothing with the selected check boxes because there is no event procedure inside CONTROLS.VBP that does any work when the user selects a check box. The check boxes exist in that program only to illustrate how they operate.











Warning: Most, but not all events, are user-triggered. Some internal Windows events can take place that trigger actions. Likewise, you can direct a program to respond to timed intervals, such as ticking a clock forward every second. The interval of time would be an event in that case.







Is all this talk about events and event procedures getting technical? Actually, you will see that the implementation of event capturing and event procedures is extremely easy. The Visual Basic environment is set up to create event procedures for you when you request them. The bottom line is this: When you want your Windows program to respond to an event, make sure that you write an event procedure for it. If you want to ignore certain events, don't write event procedures for them.











Tip: Most of the events that you want to handle are obvious. For example, if you add a command button control to a form, you want to do something when the user clicks the command button. However, if the user tries to drag the command button with the mouse, you probably want to ignore that event because the user should rarely be allowed to move controls during the execution of the program.















Review: Almost anything that can happen during the execution of a Windows program can be an event. Once you design a Windows program form and place controls on it, you must write code that responds to events. That code is made up of event procedures. In a way, each event procedure is like a miniature program that you write for each control whose event should cause an action to take place.















Control Properties











Concept: All controls are different and work differently. You use different controls for different things. Even among controls of the same type, however, differences exist. Those differences reside in the control properties.















Definition—A property determines how a control differs from other controls.







Consider the three controls shown in Figure 4.2. All three controls are command buttons even though they all look different. The user can click any of them, but each has a different set of properties.



Figure 4.2. Three command buttons with different properties.



The top command button is rather fat. The second command button is much wider than the top one, and no shortcut keystroke is available. Its caption is displayed in a special font style. The third command button is very small, and its caption is italicized. Because small italics on command buttons are not always easy to read, be careful about using them with small controls.











Tip: Less clutter is always better.







Adding too much of anything is usually worse than better. The application often requires that command buttons differ from their default size but try to stay as consistent as possible. It is rarely a good idea to put more than one font on more than one command button that appears on the same form.



One of the most important steps you take when you write Visual Basic programs is setting control properties. When this book teaches you how to add a new control to an application, you will learn about virtually all of its properties. The next unit, for instance, shows you how to place command buttons. Before you learn about placement, though, you will read about more than 20 command button properties.











Note: Rarely will you have to change all the properties of a control when you place the control on the form. Nevertheless, if you see every property that is available when you learn a new control, you will know what you can—and cannot—do with it.















Even Forms Have Properties: Visual Basic programmers use the generic term object for controls that they place on the form. Actually, even the form is an occurrence of an object. The word object means different things in different computer languages. Although faintly related, a Visual Basic object has little to do with the objects that you find in object-oriented programming languages such as C++.

Every object in a Visual Basic program has properties. Even the forms have properties. As you can see from Figure 4.2, you can add descriptive titles to forms. The title of a form is one of its property settings. The background color is another property that you can set.















Tip: Where do you add properties for controls?















In the Properties window. (Good name, huh?)















Review: Each control has a different set of property values. You often set initial property values when you place controls on the form. During the execution of the program, your code also often changes property values. The CONTROLS.VBP application, for example, changes a command button's caption property from Press Me to Once Again and back to Press Me. I added the original Press Me caption when I added the command button to the form. Then I used code to change the caption during the program's execution. What enables Visual Basic to know when to change the caption? When the user presses the command button, a command button click event occurs. Then the event procedure written for that particular event changes the caption. Read on, true Visual Basic believer, and you will see that event procedures are neither as difficult, nor as complicated, as they might first seem.















Naming Conventions











Concept: Although you will learn all about control properties throughout this book, one control property is worth learning about early on—the Name property. All controls have a Name property. The Name property labels each particular control. Without a unique name, you could not distinguish one control from another inside the Visual Basic code. Although Visual Basic assigns default names to all controls, get in the habit of changing those names to something more descriptive so that you can remember them more easily as you add to the program.















Definition—A naming convention is a set of naming rules.







The first property that you should always set is the Name property. This unit does not tell you how to set the Name property; that is covered in the next lesson. You must know in advance, however, that Visual Basic programmers do not arbitrarily assign names to controls. Programmers who want to make their programming lives less stressful follow prescribed naming conventions when they choose names for their controls.



A convention is not just a group of people gathered for the weekend. A convention is a standard set of rules that you follow. You are possibly already familiar with naming conventions—for example, the file-naming conventions used in pre-Windows 95 and DOS-based computers (up to eight characters for the name and up to three characters for the extension). In Visual Basic, the naming convention for controls is simple. When you decide on a name for your control, be sure to stay within these boundaries:





Names can be as short as one character or as long as 40 characters.





Names must begin with a letter of the alphabet and can be in either uppercase or lowercase letters.





After the initial letter, names can contain letters, numbers, or underscores.















Definition—A reserved word is a Visual Basic command.









Names cannot be the same as a reserved word. Appendix C lists all the reserved words in Visual Basic.





Names should make sense. For instance, although you could name an exiting command button Rose, cmdExit is better; it is self-documenting and easier to remember.







The following are valid names:







cmdExit







ListBoxJan







Nov95Combo







TitleScreen





and these are not:







Select







723







cmdExit&Leave





Select is a Visual Basic command. 723 does not begin with a letter of the alphabet. cmdExit&Leave contains an invalid character, the ampersand (&).











Warning: Even though the underscore is a valid character, programmers generally prefer not to use the underscore because it sometimes can look like a minus sign.

Many programmers use hump notation—mixing uppercase and lowercase letters in names that contain several words. The term hump comes from a camel's back, which the uppercase letters in the name sort of resemble. For example, cmd_Add_Sales is a valid name, but cmdAddSales is just as readable and it does not contain the underscore characters that sometimes lead to confusion.







Learn these naming rules well. The naming rules apply not only to Name properties but also to other aspects of Visual Basic, such as variables and procedures.











Write Once, Maintain Often: Rarely are you finished with a program after you write it. You usually have to update the program to reflect changes in the environment in which you use the program. When you update a program already written, you are doing what is called program maintenance.

For example, if you wrote an accounting program for a small company that merged with a second firm, the accounting department might have to keep both companies separate until the current fiscal year ends. You must modify the program so that the program distinguishes between the two companies and keeps two sets of data. The more time you spend giving meaningful names to controls, the less time you will spend later trying to figure out what each control is for. It is obvious that a control named cmdComputeProfit triggers the computation of a profit calculation.







I strongly suggest that you adopt the standards for naming control prefixes listed in Table 4.1. Table 4.1 shows the three-letter prefix that you should add to the front of a name when you name a control. The prefix describes what the control is. Therefore, from the name itself, you know what kind of control you are working with. Of course, if you placed the control on the form and named the control to begin with, you would know what kind of control you are adding. When you add code to event procedures later, however, the three-letter prefix helps you keep the kinds of controls straight and it prevents you from trying to write an incorrect event procedure for a control that does not produce that particular event.











Note: Table 4.1 lists all the naming conventions for controls and forms, including those controls that you do not know yet.













Table 4.1. Standards for naming control prefixes.











Prefix





Control





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





ole





OLE client





opt





Option button





pic





Picture box





shp





Shape





tmr





Timer





txt





Text box





vsb





Vertical scroll bar

Here are some control names that use the three-letter prefixes from Table 4.1:







frmOpening







lstSelections







chkBooksInPrint





When users move from DOS to Windows, they often complain that Windows is different and hard to learn and use. They are correct that Windows is different, but there is much disagreement on how difficult and hard-to-use a Windows environment is.



Even if you accept that Windows is hard to learn and use, you have to learn the Windows interface only once. That means that after you master a Windows program, such as the Visual Basic programming environment or Microsoft Excel, every other Windows program behaves in almost exactly the same manner. Almost every Windows program contains an Exit command on a File pulldown menu, displays the same File Open dialog box, displays a white background. Software developers do not have to follow these standards, but users are more likely to learn the programs if they do.











Review: When you name controls, don't assign arbitrary names or even stick to the name that Visual Basic assigns; you won't like Visual Basic's suggestions. Select a name that indicates the purpose of the control, and use one of the three-letter prefixes described in Table 4.1. By following such standards, you will ensure that your program is easier to maintain down the road.















More Consistency: Named Constants











Concept: Add consistency to your Visual Basic programs by using named constants.







Over time, you incorporate many common elements in your Visual Basic programs. Perhaps you have written a set of routines in the Visual Basic language that you want to make available to several Visual Basic programs. As you already know, by adding files to the project window, you, in effect, add those files to the resulting application.











Warning: Previous versions of Visual Basic used the CONSTANT.TXT to hold named constants but Visual Basic 4.0 knows named constants and you never need to load CONSTANT.TXT. Therefore, if you load an older Visual Basic application but encounter an error that reads CONSTANT.TXT not loaded, you may have to edit the named constants originally found in CONSTANT.TXT to the new version 4.0 named constants. When you run the application, Visual Basic informs you if it runs across any named constants that are not recognized.















Definition—A named constant is a constant value with a name that is easy to remember.







There will be several times when you have to set various controls to specific values from a list of possibilities. For example, a checkbox control can be checked, grayed, or unchecked. If you set the Value property of a checkbox to 0, Visual Basic sets the property value to Unchecked. If you set the Value property to 1, Visual Basic sets the property value to Checked. If you set the Value property to 2, Visual Basic sets the Value property to Grayed. Instead of setting properties with those hard-coded values, you can use descriptive named constants such as vbChecked, vbUnchecked, and vbGrayed.



The designers of Visual Basic took most control property values and assigned names to them so that you can use either the names, which are usually easier to remember than actual numbers, or the values themselves. Once you get used to using named constants, you will rarely use the actual values.











Warning: Don't fret. The use of named constants will make a lot more sense when you begin building your own applications. For now, remember that the named constants in Visual Basic 4.0 sometimes, but not always, begin with the letters vb. This book will introduce several common named constants to you.















Review: Named constants are generally easier to remember, especially once you familiarize yourself with Visual Basic and common control properties. By using the named constants as opposed to numeric values for property values, you'll make your programs easier to understand and maintain.















Quick to the Draw!











Concept: Finally! You will now use Visual Basic to create your very own fully working Windows program. If you don't think that you know enough about Visual Basic to write programs, hang on because you will see how easy creating a program can be. Follow these steps to create your first Visual Basic application:









Select File New Project to open a new application. Visual Basic opens a new project and a blank Form window on which you will place controls.





Double-click the label control. Remember that the label control is the uppercase A on the Toolbox window. A blank label control (with the terrible default Name property of Label1) appears in the center of the Form window.





Press F4 to bring the Properties window into view.





Scroll the Properties window to the Caption property. The Caption property, by default, contains the name of the label. Because the Caption property holds the label's text, you should change the text. Click the Caption property, type My First! and press Enter. As Figure 4.3 shows, the label immediately displays the new caption.







Figure 4.3. After changing the label's caption.





Click and hold the mouse cursor over the label that you just added, and drag the label towards the top of the Form window. Leave about an inch between the top edge of the label and the top edge of the window. Center the label under the title bar. By default, the form's title is the name of the form, Form1. (You will change control names from their default names in the next unit.)





Double-click the command button control on the Toolbox window. A command button appears in the center of the Form window.





Type the following exactly as you see it: E&xit. The ampersand (&) causes the x to be underlined, as you can see when you look at the resulting command button's caption. The Caption property is the first property that changes because the last property that you changed when you worked with the label control was its Caption property.





Center the command button by dragging the command button a little to the left. Once you center the command button, double-click it. Immediately, Visual Basic opens a Code window as shown in Figure 4.4.







Figure 4.4. The Code window opens when you double-click a control.





Visual Basic knows that you want to write an event procedure that executes whenever the user clicks the command button. You can tell that Visual Basic opened an event procedure for a command button keypress because the name of the procedure is Command1_Click(). (Don't worry about the parentheses right now.) An event procedure always takes the following format:

ControlName_EventName()

The default name for a new command button (until you change the Name property) is Command1, and the event that triggers when the user clicks a command button is Click. Therefore, the code that handles this command button's click is Command1_Click().





The two lines that Visual Basic adds to the event procedure are called wrapper lines or wrapper code because they wrap around the code you add to the event procedure. For this event, simply press Tab and add End. The full event procedure should look like this:

Sub Command1_Click()

End

End Sub



That's it. To see your handiwork, close the Code window and press F5 to run the application you just created. The application's form appears on the screen with its two controls, as shown in Figure 4.5.

To terminate your application and return to Visual Basic, click the Exit command button. As soon as you click the command button, the event procedure that you added executes. The End statement that you added to the event procedure also executes. The sole purpose of End is to terminate the application.







Figure 4.5. Your first application works like a charm!











Other Command Button Events: Other events are possible with command buttons. Open the Code window and look at the other event names. Click the down arrow at the right of the Code window's Proc: dropdown list. Scroll through the list. You will see that there is a DragDrop event for when the user drags the command button with the mouse and a KeyDown button for when the user presses the command button's shortcut key, among others.

Other kinds of controls, such as the list box or label control, might have events that are identical to those of the command button control, but the other controls also have different events. The Code window's Object: dropdown list always contains a list of the application's current objects—such as the form and any controls you have added—and the Proc: dropdown combo list contains a list of events for each of the controls that you highlight in the Object: list.







If you want, you can save this application. However, the disk that comes with this book contains the full application; it is called MYFIRST.VBP. Therefore, if you save your work, save it under a different filename.



When you save your applications, Visual Basic wants you to name both the form and the entire project. Usually, especially for the one-form applications that you will write throughout most of this book, you name the form the same name as the project, but both have different filename extensions. Suppose that you want to save the project under the name FIRST. To save the project, follow these steps:





Select File Save Project. Visual Basic opens the Save As dialog box for the form. Type FIRST and press Enter. Visual Basic adds the .FRM extension.





Visual Basic now displays the Save Project As dialog box. Type FIRST and press Enter to save the project. Visual Basic adds the .VBP extension.





You can now exit Visual Basic and take a deserved rest.















Review: With a few keystrokes and mouse clicks, you can create a fully working Visual Basic application. If you rerun the MYFIRST.VBP application, you will see that you can maximize, minimize, and resize the application's window. Visual Basic automatically adds a control icon in the upper-left corner of the window with which you can control the application from the Windows system level.















Homework











General Knowledge





What is an event?





Why are GUI-based programming environments such as Windows event-driven?





True or false: Windows passes all events that happen in your program to Visual Basic.





What are properties?





What must you write to handle events?





Name two properties for any control that you can think of after reading this unit.





True or false: Forms have properties.





True or false: Forms are objects.





Which window do you use for changing property values?





What is program maintenance?





What advantage does using a three-letter prefix offer?





Why should you write Windows programs that look and work in a manner that is consistent with other Windows programs?





What is meant by hump notation?





What two letters do named constants usually begin with?





What are named constants?





True or false: Visual Basic assigns well named control names by default.





How can you open a Code window for a control's primary event property?





How are event procedures named?





What are the first and last statements in an event procedure often called?





What Visual Basic command terminates a running program?





What does the Code window's Object: dropdown combo list contain?





How does the filename of the form differ from the name of the project?





What object does frmStartUp probably describe?





What object does cboNameChoice96 probably describe?





What object does cmdPrintIt probably describe?















Find the Bug





Victor the Visual Basic programmer just got a new CD-ROM with tons of great fonts. Victor decides to use a different font for every word on his form. Please help show Victor why the multiple fonts can be a bad idea.





Describe what is wrong with each of these control Name properties:









End





96JanSalesList





cmdStar$





July-List

















Extra Credit



Create a new project that contains two control buttons. Add a Beep statement to the wrapper of the first button's Click event procedure, and change the Caption property to Ring a Bell. (Beep is a command that rings the PC's bell.) Change the second command button's Caption property to Exit, and type End for the Click event procedure. Run the program and test your results.




















Wyszukiwarka