MY PODCAST ON VISUAL PROGRAMMING
Click HERE
Click on the video to watch my screenpal on youtube
MY INFOGRAPHICS ON VISUAL PROGRAMMING
Visual Basic Programming Questions on Kahoot
Click on the link below
Click here to attempt: VB. Quiz
or
Click this link: https://kahoot.it/challenge/07338694?challenge-id=5a81db6b-689f-445c-a39c-315b4d7821f8_1717774004429
Game Pin: 07338694
1.1 WHAT IS VISUAL BASIC?
Visual Basic is an object-oriented programming development system for creating applications that run under any of the Microsoft Windows environments. It has the following two major components:
1. An extensive collection of prewritten tools, called controls. These controls are accessible as icons within a graphical programming environment for creating customized windows components (e.g., menus, dialog boxes, text boxes, slide bars, etc.).
2. A complete set of program commands, derived from Microsoft’s implementation of the classical Basic pro- gramming language. The command set includes features that embrace contemporary programming prac- tices.
The overall approach to Visual Basic programming is twofold:
1. Create a user interface that is appropriate to the particular application at hand.
2. Add a group of Basic instructions to carry out the actions associated with each of the controls.
1.2 EVENTS AND EVENT PROCEDURES
In traditional computer programs, the actions are carried out in a prescribed order. This order may be sequen- tial, corresponding to the order in which the instructions are written, or it may depend on the outcome of one or more logical tests. In either case, the order of execution is determined internally within the program.
Visual Basic, on the other hand, is based upon an event-driven paradigm, in which each feature included within the program is activated only when the user responds to a corresponding object (i.e., an icon, a check box, an option button, a menu selection, etc.) within the user interface. The program’s response to an action taken by the user is referred to as an event. Note that the user initiates the event, but it is the program’s re- sponse that actually defines the event. The group of Basic commands that brings about this response is called an event procedure.
1.3 OBJECT-RELATED CONCEPTS
In addition to events and event procedures, you must understand the meaning of each of the following terms:
Forms: In Visual Basic, a window is called a form. Each form includes a title bar at the top. A form may also include a menu bar, a status bar, one or more toolbars, slide bars, etc. A user area (called a client area) occupies the remaining space within the form. Some applications are based upon a single form, while others require two or more forms. Fig. 1.1 shows a simple form containing two command button controls and a text box control (see below).
Controls: The icons with which the user interacts are called controls. Commonly used controls include com- mand buttons, option buttons, check boxes, labels, text boxes, picture boxes and menus. The user will typically activate a control (e.g., click on a command button) to produce an event.
Objects: Forms and controls are referred to collectively as objects. Most objects are associated with events; hence, objects may include their own unique event procedures. Objects are also associated with their own properties and methods (see below).
Properties: Objects include properties that generally define their appearance or behavior. The choice of prop- erties depends on the type of object. For example, the name, caption, height, width, background color, location and font are some of the more common properties associated with a command but- ton.
Methods: Some objects also include special program statements called methods. A method brings about some predefined action affecting the associated object. For example, show is a method that can be used with a hidden form to make it visible.
1.1 THE VISUAL BASIC PROGRAM DEVELOPMENT PROCESS
In general terms, the process of writing a Visual Basic program consists of several steps. They are:
1. Decide what the program is supposed to do. Be as specific as possible. (Remember, however, that you may change your mind, perhaps several times, before you are finished.)
2. Create a user interface, using Visual Basic’s program development tools. This generally involves two re- lated activities:
(a) Draw the controls within their respective forms.
(b) Define the properties of each control.
3. Write the Visual Basic instructions to carry out the actions resulting from the various program events. This generally involves writing a group of commands, called an event procedure, for each control (though cer- tain controls, such as labels, do not have event procedures associated with them).
4. Run the program to verify that it executes correctly.
5. Repeat one or more steps if the results are incorrect, or if the program does not respond as you had in- tended.
Be prepared to carry out several cycles before you’re satisfied with the final result. Remember that computer programming is a detailed, creative process that requires patience, skill and ingenuity. At times the program development process can become frustrating (as, for example, when your program does not execute correctly, or it does not execute at all because of hidden, hard-to-find programming errors). At such times it is often best to take a break, set your work aside for a while, and come back to it later.
VISUAL PROGRAMMING QUIZIZZ
1.1 REQUIRED COMPUTER SKILLS
In order to use Visual Basic and derive some benefit from this book, you should have some proficiency in all of the following:
1. Familiarity with one of the Microsoft Windows operating systems (e.g., Windows 2000/98/95/NT, etc.). In particular:
(a) Entering windows.
(b) Using a mouse.
(c) Accessing an application (specifically, Visual Basic).
(d) Leaving windows.
(e) Getting on-line help.
2. Managing files within Windows (locating files, opening files, editing files, saving files, copying files, mov- ing files, deleting files, etc.).
3. Installing new applications (in case Visual Basic has not already been installed, or needs to be reinstalled).
We will not discuss these issues further – it is assumed that you already have the requisite skills. We will, how- ever, discuss file management within Visual Basic later in this book, as the need arises.
1.2 LOGICAL PROGRAM ORGANIZATION
Virtually all nontrivial computer programs involve three major tasks. They are:
1. Entering input data (supplying information to be processed).
2. Computing the desired results (processing the input data).
3. Displaying the results (displaying the results of the computation.
Each step may be complex; its implementation may therefore require considerable time and effort.
In Visual Basic, the first and last steps (data input and data output) are accomplished through the user in- terface. Thus, it is important to design a user interface that will accept input data and display output in a man- ner that is logical and straightforward for the particular application at hand. In many applications, the design of the user interface is the most complicated part of the entire program development process, though the controls built into Visual Basic simplify this process considerably.
The second step (computation) is usually carried out by a series of Visual Basic instructions, embedded in one or more independent event procedures. The selection and order of these Visual Basic instructions are de- termined by an appropriate algorithm, i.e., a logical and orderly computational strategy for transforming the given input data into the desired output data. In many realistic applications, this step (i.e., the implementation of the algorithm) can be very complicated, challenging the abilities of very skilled programmers.
1.3 VISUAL BASIC PROGRAM COMPONENTS
In Visual Basic, a program is referred to as a project. Every Visual Basic project consists of at least two sepa- rate files – a project file (whose extension is .vbp), and a form file (with extension .frm). Some projects include multiple form files and other types of files, such as class module (.cls) files, standard module (bas) files, re- source (.res) files, and ActiveX control (.ocx) files. Thus, the development of a Visual Basic project involves keeping track of several different files, and accessing these files individually within the Visual Basic environ- ment, as needed.
1.4 THE VISUAL BASIC ENVIRONMENT
To enter the Visual Basic environment, click the mouse on the Visual Basic icon which appears on your Win- dows Desktop. This will result in the opening group of windows shown in Fig. 1.2. You may then enter the workspace for a new project by selecting New/Standard.EXE, or by selecting New Project from the File menu (see below). Or, you may open an existing project by selecting either the Existing tab or the Recent tab, and then selecting the particular project that is of interest. Still another way to open an existing project is to select Open Project from the File menu, and then select the particular project of interest.
Fig. 1.2 The Visual Basic opening group of windows
If you choose to create a new project, you will see a group of windows similar to that shown in Fig. 1.3.
The principal items are described below:
TITLE BAR
The top line is called the Title Bar. It includes the project name, an icon that closes Visual Basic at the left, and icons that minimize the group of windows, change the size of the group, or close Visual Basic on the right. We will discuss these icons later, as the need arises. For now, however, note that you can exit from Visual Basic by clicking on the left icon and then selecting Close from the resulting drop-down menu, or by clicking on the rightmost icon (´).
MENU BAR
The second line is called the Menu Bar. Selecting one of the choices (File, Edit, View, Project, Format, . . . Help) causes one of Visual Basic’s drop-down menus to appear. These menus present logical groupings of Vis- ual Basic’s individual features. For example, the File menu includes selections for opening new or existing VB projects, saving the project, saving the currently active window, printing the currently active project, running (executing) a Visual Basic project, opening recently accessed projects, and so on.
Fig. 1.3 The Visual Basic new project environment
TOOLBAR
The third line is called the Standard Toolbar. The icons on this line duplicate several of the more commonly used menu selections that are available via the drop-down menus accessed from the Menu Bar. For example, the Standard Toolbar contains icons that will open an existing project; save the current project; cut, copy and delete; undo the most recent changes; start, pause and end program execution; and add/delete windows from the current overall environment. All of these features can be accessed via drop-down menus. Hence, the toolbar icons do not offer any new or unique features, but their use is convenient, since the icon-based features can be selected with a single mouseclick.
Other toolbars (Debug, Edit and Form Editor) can be accessed by selecting Toolbars from the View menu.
The Standard Toolbar can also be removed in this manner.
FORM DESIGN AND PROJECT CONTAINER WINDOWS
The Form Design Window is where the user interface is actually designed. This is accomplished by selecting the desired Control Icons from the Toolbox (see below) and placing them in the Form Design Window. Each control can then be moved (place the mouse over the icon and drag) or resized (activate the icon and drag one of the small surrounding squares), and its properties can be reassigned as required (see below).
The entire form (i.e., the entire Form Design Window) can be moved within the surrounding Project Con- tainer Window (by placing the mouse over the form and dragging), or it can be resized (by activating the mouse and then dragging one of the small surrounding squares). Both windows can also be closed, minimized, or resized by clicking on the appropriate icons in their respective Title Bars.
TOOLBOX
The Toolbox contains icons that represent commonly used controls, such as a label, text box, command button, picture box, frame, check box, option button, file list box, and so on. You can select a control from the Tool- box and place it in the current Form Design Window by double-clicking on the control icon (thus placing the control in the center of the window), or by clicking once on the control icon, then clicking on the desired loca- tion within the Form Design Window and dragging the mouse so that the control has the desired size.
Once a control has been placed in the Form Design Window, the associated code (i.e., the associated Vis- ual Basic instructions) can be viewed or edited by double-clicking on the control.
PROPERTIES WINDOW
We have already learned that every object has properties associated with it. Each object has its own unique list of prSoperties. The Properties Window allows you to assign or change the properties associated with a particular object (i.e., a particular form or control). To do so, active the object by clicking on it; then choose from the corresponding list of properties shown in the left column of the Properties Window. Once you select a prop- erty, the adjoining box in the right column may change its appearance, showing a drop-down menu so you can choose from a list of permissible values.
PROJECT WINDOW
The Project Window displays a hierarchical list of the files associated with a given project. These files repre- sent individual forms and modules. You can display a form or module within the Project Container Window by double-clicking on the corresponding icon within the Project Window. Also, you can select either the Object View or the Code View by clicking on one of the two leftmost icons within the toolbar at the top of the Project Window.
CODE EDITOR WINDOW
If you select Code View within the Project Window, or if you double-click on a control icon within the Form Design Window, the Code Editor Window will open, displaying the Visual Basic code associated with the cur- rently active form. Fig. 1.4 shows the Code Editor Window containing two different event procedures (i.e., the Visual Basic code associated with two different command buttons). Ignore the individual Visual Basic instruc- tions for now. Notice, however, the two list boxes at the top of the window. The leftmost list box (showing Command2 in Fig. 1.4) is the Object Listbox; it allows you to select the event procedures associated with a particular object (e.g., a particular command button, form, label, text box, etc.). The rightmost list box (show- ing Click in Fig. 1.4) is called the Procedure Listbox; for the current object, it allows you to select the event procedure associated with a particular type of event (e.g., Click, DragDrop, KeyDown, MouseDown, etc.).
Fig. 1.4 The Code Editor Window containing two event procedures
FORM LAYOUT WINDOW
The Form Layout Window allows you to specify the screen location of the forms within a project. To change the form location, simply drag the form icon to the desired position.
IMMEDIATE WINDOW
The Immediate Window is very useful when debugging a project. Whenever you enter a variable or expression within this window, the corresponding value will be shown immediately.
REPOSITIONING, RESIZING, DELETING, ADDING, AND DOCKING WINDOWS
Any of the individual windows can be repositioned (by activating the window and then dragging it to the de- sired location), resized (by activating and then dragging an edge or corner), and deleted (by clicking on the ´ in the upper right corner). A window can be added by selecting the window name from the View menu.
The interface may become messy if several windows have been moved and/or resized. When this happens, Visual Basic allows the windows to be returned to their orderly, preassigned position. This is called docking. Docked windows are always aligned alongside their neighbors, and they are always visible.
To dock a window that has been moved from its preassigned position, simply double-click on the win- dow’s title bar. For any window, docking can be overridden by selecting Options/Docking from the Tools menu, and then selecting or deselecting the appropriate check boxes.
1.1 OPENING AN EXISTING VISUAL BASIC PROJECT
We have already seen that an existing project can be accessed by locating the project name listed under the Existing or the Recent tab within the New Project window (see Fig. 1.2), or by locating the project via File/Open Project. Once the project is opened, however, the Form Design Window may not be visible within the Project Container Window. To access the Form Design Window, you may have to expand the Forms icon within the Project Window as shown in Fig. 1.5, and then select the desired form. Double-click on the form icon to show the Form Design Window.
Fig. 1.5 Activating a form within the Project Container Window
1.1 SAVING A VISUAL BASIC PROJECT
Saving a project can be tricky in Visual Basic because it involves saving multiple files.
To save a new Visual Basic project for the first time, choose Save Project As from the File menu. You will be prompted separately for a form name (i.e., the name of the .frm file) and a project name (the .vbp file). Usu- ally, the same name is given to both files.
To save an updated version of a previously saved project, click on the Save Project button in the Toolbar (see Fig. 1.6), or select Save Project from the File menu. This will cause the current version of the project files to be saved under their existing names.
To save a previously saved project under a different name (this is the tricky part), you must save each file separately under its new name. Thus, you should first save each form file under the new name, and then save the project file under the new name. If you simply save the project file under a different name, the form files will retain their old names; this may cause problems when switching between the old version and the new ver- sion of the project.
1.1 RUNNING A VISUAL BASIC PROJECT
To execute a Visual Basic project, simply click on the Start button in the Toolbar (see Fig. 1.6), or select Start from the Run menu. The execution can be temporarily suspended by clicking on the Break button, or by select- ing Break from the Run menu. The execution of a paused project can then be resumed by clicking on the Run
button, or by selecting Continue from the Run menu. To end the execution, simply click on the End button, or select End from the Run menu.
1.2 GETTING HELP
Visual Basic includes many intricate concepts, predefined identifiers, detailed syntactic requirements, etc. – more than you can remember at any one time. Fortunately, Visual Basic also includes an excellent on-line help facility, which will answer most questions and provide detailed information, with examples, of various Visual Basic features.
To access the help feature, press function key F1 or select Contents, Index or Search from the Help menu. Fig. 1.7 shows the help window that is obtained by pressing F1, or by selecting Help/Index. Notice the tabs at the left side of the window, which allow you to select the Contents, Index, Search or Favorites window for viewing.
Fig. 1.7 The Help window
1.1 A SAMPLE VISUAL BASIC PROJECT
The following example shows the overall process used to create a Visual Basic project. Our primary emphasis is on the use of controls to create a user interface. When reading through this example, try to focus on the “big picture” and ignore the details, which are discussed in later chapters.
EXAMPLE 1.1 AREA OF A CIRCLE
In this example, we create a project that calculates the area of a circle. The user enters a value for the radius, and then clicks on the Go button. The corresponding area will then be displayed, as illustrated in Fig. 1.8.
Fig. 1.8
We begin by opening Visual Basic and selecting Standard EXE from the New tab in the New Project menu (see Fig.
1.2). This causes a blank Form Design Window to be displayed, as shown in Fig. 1.9 (see also Fig. 1.3).
We then place the necessary controls in the Form Design Window. In particular, we place two labels, two text boxes, two command buttons, and a geometric shape on the form, as shown in Fig. 1.10. Each control is selected from the Tool- box, which is positioned to the left of the Form Design Window (see Fig. 1.3). Note that the controls are automatically called Label1, Label2, Text1, Text2, Command1, and Command2, and the Form Design Window is called Form1. The geo- metric shape has no default name.
Each control can be selected two different ways. You can click on the desired control icon within the Toolbox, then click on the control’s location within the Form Design Window, and then drag the mouse until the control has the desired size and shape. Or, you can double-click on the desired control icon within the Toolbox, placing the control at the center of the Form Design Window. You can then drag the control to its desired location and resize the control by dragging one of its edges or corners. (In Fig. 1.10, the controls have been placed in their approximate desired locations but they have not been resized.) If you change your mind, you can delete a control by highlighting the control (clicking on it) and then press- ing the Delete key.
Defining the Interface Control Properties
The next step is to define an appropriate set of properties for each control. Since the controls already have default proper- ties associated with them, the actual process generally involves changing only a few of the defaults.
The properties associated with each control are displayed in the Properties Window (see Fig. 1.11 below). To view the properties, simply activate the control by clicking on it. You may then choose a property from the list shown in the left column of the Properties Window. The current value of that property is shown in the adjoining location within the right column.To change the value of the property, either type in a new value, or select from the list of values shown in the drop- down menu.
In Fig. 1.11, for example, the active control is Label1. The Properties Window shows the properties associated with this control. The Caption property is highlighted, showing Label1 as the current (default) value. If we change this value to Radius:, then the window will appear as in Fig. 1.11. Note that the new value for the Caption is Radius:. This new value also appears in the Form Design Window (see Fig. 1.12), where the control is now shown as Radius:.
The (nondefault) property values for each object (i.e., for the form and each of the seven controls) are summarized be-
low.
Object Property Value
Form1 Name Caption “Circle”
“Area of a Circle”
Label1 Caption Font “Radius:”
MS Sans Serif, 10-point
Label2 Caption Font “Area:”
MS Sans Serif, 10-point
Object Property Value
Text1 Font MS Sans Serif, 10-point
Text2 Font MS Sans Serif, 10-point
Command1 Caption Font “Go”
MS Sans Serif, 10-point
Command2 Caption Font “End”
MS Sans Serif, 10-point
Shape Shape 3 – Circle
BorderWidth 2
FillStyle 0 – Solid
FillColor Medium Blue
Defining the Event Procedures
The last step is to write the Visual Basic commands that comprise the event procedures. In this example, only the command buttons, labeled Go and End in Fig. 1.13 (originally labeled Command1 and Command2, as shown in Fig. 1.12), have event procedures associated with them. Hence, we must define an event procedure for each of these command buttons.
To define the event procedure associated with the Go button, double-click on the button. This will cause the Code Editor Window to be displayed, as shown in Fig. 1.14. Within this window, the first and last line of each event procedure (e.g., Private Sub Command1_Click() and End Sub) are provided automatically, separated by a blank line. The actual Visual Basic commands must be inserted between these two lines.
In the current example, we add the following commands to the first event procedure:
Dim R As Single, A As Single
R = Val(Text1.Text) A = 3.141593 * R ^ 2
Text2.Text = Str(A)
The first line is a variable declaration, stating that R and A are single-precision, real variables. The remaining three lines are assignment statements; that is, the information represented by the item on the right-hand side of the equal sign is assigned to the item on the left-hand side. Thus, the first assignment statement assigns the current value of the radius, entered from text box Text1, to the variable R. The second assignment statement computes the area and assigns this value to the variable
A. The third assignment statement converts the value of the area to a string and then assigns this string to the Text property of Text2.
Similarly, we add the command
End
to the second event procedure. This command simply terminates the computation.
Here is a more detailed explanation of the first event procedure (skip this if you wish – it will all be discussed later in this book): Text1 is the name of an object (in this case, a text box) and Text is the name of the object’s associated property. Thus, Text1.Text refers to the text associated with text box Text1. Similarly, Text2.Text refers to the text associated with text box Text2. Val and Str are library functions. Val returns a numerical value from a string argument. Str does just the opposite – it returns a string from a numeric argument.
When the program is executed, the user must enter a value for the radius in text box Text1 and click on the Go button. The radius (Text1.Text) is then converted to a numerical value, represented by the variable R. The area (represented by the variable A) is then calculated, converted to a string, and assigned to Text2.Text. This string is then displayed in text box Text2.
Fig. 1.15 shows the completed event procedures for this project. Note that the added commands are indented, relative to the first and last lines of each event procedure. This is not essential, but it is considered good programming practice. The indentation allows each event procedure to be quickly identified and easily read.
Fig. 1.15
Project Execution
When the project is executed (by clicking on the Start button in the menu bar), the window shown in Fig. 1.16 appears. Entering a value for the radius and clicking on the Go button results in a display of the corresponding area, as shown in Fig. 1.17.
The computation is ended by clicking on the End button. The Form Design Window shown in Fig. 1.13 then reappears.
Review Questions
1.1 What are the two major components within the Visual Basic programming development system?
1.2 What two primary activities are required when creating a Visual Basic program?
1.3 What is an event? What is an event procedure?
1.4 In Visual Basic, what is a form?
1.5 In Visual Basic, what is meant by controls? Name some common controls.
1.6 What are objects? Name some common Visual Basic objects.
1.7 What are object properties? Name some common properties of Visual Basic objects.
1.8 In Visual Basic, what is meant by a method?
1.9 Describe the principal steps involved in the Visual Basic project development process.
1.10 Most computer programs involve what three major tasks?
1.11 Open up Visual Basic on your computer. Then identify each of the following:
(a) Title Bar
(b) Menu Bar
(c) Drop-down menus
(d) Standard Toolbar
(e) Form Design Window
(f) Project Container Window
(g) Toolbox
(h) Properties Window
(i) Project Window
(j) Code Editor Window
(k) Form Layout Window
(l) Immediate Window
1.12 Summarize how each of the following operations is carried out:
(a) Repositioning (relocating) a window
(b) Resizing a window
(c) Deleting (closing) a window
(d) Adding a new window
1.13 What is meant by “docking” a window? How is window docking is carried out?
1.14 How is an existing Visual Basic project opened?
1.15 How is a Visual Basic project saved?
1.16 How is a Visual Basic project executed? How is the project paused during execution? How is it resumed? How is the execution ended?
1.17 How is the on-line help feature accessed?
Programming Problems
1.18 Re-create the project given in Example 1.1 using your own version of Visual Basic. Verify that the pro- ject executes correctly. Then change the project in the following ways:
(a) Change the label captions to Enter the radius below: and The area is:.
(b) Change the background colors of the form and the text boxes. (Choose your own colors.)
(c) Change the command button captions to Execute and Quit.
(d) Raise the lower label and the lower text box so that they are closer to the upper label and text box.
(e) Move the command buttons to the bottom of the form and align them horizontally.
(f) Resize the form and rearrange the controls relative to one another so that the form has an overall pleasing appearance.
(g) Access the on-line help for the Val function (select Index/Val function from the Help menu). Then do the same with the Str function.
1.19 Modify the project given in Example 1.1 so that it calculates both the area and the circumference of a circle from the given value of the radius. Display each calculated value in a separate text box. Experiment with the project so that it runs correctly and has a pleasing appearance. Access the on-line help feature to obtain assistance with programming details.