Before you start coding
The most important (and often overlooked) part of creating an application in Visual Basic is the design phase. The need to design a user interface for the application is obvious; the need to structure the code is less obvious. Different methods of constructing applications can result in differences in application performance and code maintainability and usability. Visual Basic application code is organized in a hierarchical manner. A typical application consists of several modules: a form module for each form in the application, optional standard modules that share code, and optional class modules. Each module contains several processes containing code: event process, Sub sub-process or Function process, and PRperty process. Determining which process belongs to which module has a certain relationship with the type of application being created. Because Visual Basic is object-based, it is helpful to think of applications in terms of the objects they represent. In this chapter, the sample application Vcr.vbp is designed based on the objects consisting of a video cassette recorder and a television set. The VCR application contains two form modules, a standard module and two class modules. The "Object Browser" can be used to examine the structure of the project (Figure 5.2).
The main form of the VCR application (frmVCR) is the visual image of the combination of the VCR and the TV screen (Figure 5.3). It consists of several objects modeled after real-world scenes. A set of command buttons (cmdPlay, cmdRecord, etc.) mimic the buttons that operate a VCR. Software VCR also includes clock (lblTime), channel indicator (lblChannel), function indicator (shpPlay, shpRecord, etc.) and picture tube (picTV). The Vcr.frm form module includes event procedures for all these objects.
In many cases there are repeated processes shared by multiple objects. For example, "pressing" the "play", "rewind" or "record" button requires the "pause" and "stop" buttons to be valid. It's better to create a shared subroutine that all buttons can call rather than repeating this code in each button's Click event procedure. If these subroutines are modified in the future, all modifications can be made by modifying them in one place. The standard module Vcr.bas contains various shared procedures.
Some parts of the VCR are invisible, such as the tape transport mechanism or the logic behind recording television programs. Likewise, some functions of software VCRs do not have visual images. These parts and functions are implemented as two class modules Recorder.cls and Tape.cls. The clsRecorder module contains the code to start the "recording" process; and the clsTape module contains the code to control the direction and speed of the "tape". The classes defined in these modules are not directly related to any objects in the form. Because they are independent code modules, a recording program can be easily rebuilt without any modifications.
In addition to designing your code structure, it is also important to establish a naming convention. By default, Visual Basic names the first form of the project Form1, the second form Form2, and so on. If you have several forms in your application, it's a good idea to give them meaningful names to avoid confusion when writing or editing code. Some naming conventions recommended by Visual Basic are listed in Appendix B, "VisualBasic Coding Conventions."
As you learn more about objects and learn to write code, refer to the VCR sample application to find examples of various coding techniques.
Code writing mechanism
Before you start writing code, it's important to understand the mechanics of writing code in Visual Basic. Like any programming language, Visual Basic has its own rules for organizing, editing, and formatting code.
code module
Visual Basic code is stored in modules. There are three types of modules: forms, standards, and classes. A simple application can have just one form, with all of the application's code residing in the form module. When the application is large and complex, additional forms must be added. You may end up discovering that there is common code being executed in several forms. Because you don't want to duplicate code in both forms, create a separate module that contains the procedures for implementing the common code. Stand-alone modules shall be standard modules. You can then build a library of modules containing shared procedures.
Each standard module, class module, and form module can contain:
statement. You can place declarations of constants, types, variables, and dynamic link library (DLL) procedures at the module level in forms, classes, or standard modules.
process. A Sub, Function, or Property procedure contains pieces of code that can be executed as a unit. These are discussed in the "Process Overview" section later in this chapter.
form module
Form modules (file extension .FRM) are the basis for most Visual Basic applications. A form module can contain procedures for handling events, general procedures, and form-level declarations of variables, constants, types, and external procedures. If you were to view the form module in a text editor, you would also see a description of the form and its controls, including their property settings. Code written into a form module is specific to the specific application to which the form belongs; it may also reference other forms or objects within the application.
Standard module
Standard modules (file extension .BAS) are containers for procedures and declarations that are accessed by other modules within an application. They can contain global (application-wide) or module-level declarations of variables, constants, types, external procedures, and global procedures. Code written in standard modules does not have to be tied to a specific application; if care is taken to refer to forms and controls not by name, standard modules can be reused in many different applications.
class module
In Visual Basic, class modules (file extension .CLS) are the basis of object-oriented programming. Code can be written in class modules to create new objects. These new objects can contain custom properties and methods. In fact, a form is just such a class module on which controls can be placed and form windows can be displayed.
Details For more detailed information about writing code in class modules, see Chapter 9, "Programming with Objects."
Note that the Professional and Enterprise editions of Visual Basic also include ActiveX documents, ActiveX designers, and user controls. They introduce new module types with different file extensions. From a coding perspective, these modules should be treated as form modules.
Use the Code Editor
The Visual Basic Code Editor is the window on which most code is written. It is like a highly specialized word processing software with many features that facilitate writing Visual Basic code. Figure 5.4 shows the "Code Editor" window.
Because you need to operate the Visual Basic code in the module, you need to open an independent "Code Editor" window for each module selected from the "Project Explorer". In each module, for each object contained in the module, the code in the module is subdivided into independent parts corresponding to the object. Use the "Object List Box" to switch between parts. In a form module, the list contains a general section, a section for the form itself, and a section for each control the form contains. For class modules, the list includes a general section and a class section; for standard modules, only one general section is displayed.
Each piece of code can contain several different procedures accessed using the Procedure List Box. The form module's procedure list contains a separate section for each event procedure of a form or control. For example, the process list of the Label control includes the Change event segment, Click event segment, DblClick event segment, and so on. Class modules only enumerate the event procedures of the class itself - initialization and termination. The standard module does not enumerate any event procedures because the standard module does not support events.
The procedure list of the module's general section only contains the only section - the declaration section, where module-level variables, constants and DLL declarations are placed. When you add subprocedures or function procedures to a module, those procedures are added to the Procedure List Box below the declaration section.
Two different views of code are available in the Code Editor window. You can view one process at a time, or you can view all processes in a module, separated from each other by lines (as shown in Figure 5.4). To switch between the two views, utilize the "View Selection" button in the lower left corner of the editor window.
autocomplete coding
Visual Basic can automatically fill in statements, properties, and parameters, making writing code more convenient. As you enter code, the editor enumerates appropriate choices, statements, or function prototypes or values. Accessed through the Options command on the Tools menu, options are available on the Editor tab of the Options dialog box that determine whether to allow or disable setting values for individual codes.
When you enter a control name in the code, the "Automatic List Member Properties" will highlight the drop-down property sheet of the control (Figure 5.5). Typing the first few letters of the attribute name will select the name from the table, and pressing the Tab key will complete the entry. This option is very helpful when you are not sure what properties a given control has. Even if you choose to disable the Automatic List Members feature, you can still use the CTRL J key combination to get this functionality.
The "Auto Quick Info" feature displays the syntax of statements and functions (Figure 5.6). After entering a legal Visual Basic statement or function name, the syntax is displayed immediately below the current line and its first parameter is displayed in bold. After entering the first parameter value, the second parameter appears again, also in bold. "Automatic quick information" can also be obtained using the CTRL I key combination.
bookmark
Bookmarks can be used in the code editor to mark certain lines of code so that you can easily return to them later. Toggling bookmarks on and off and commands to navigate to existing bookmarks can be obtained from the Edit, Bookmark menu items or the Edit toolbar.
More information For more detailed information about how to use key combinations to use various features of the Code Editor window, see "Code Window Shortcut Keys."
coding basics
This section introduces the mechanics of writing code, including how to break and merge lines of code, how to add comments, how to use numbers, and Visual Basic naming conventions.
Split a single line statement into multiple lines
You can use line continuation characters (a space followed by an underscore) in the Code window to break long statements into multiple lines. Because of the use of line continuation characters, the code becomes more readable both on the computer and in print. The following uses the line continuation character (_) to divide the code into several lines:
Data1.RecordSource=_
SELECT*FROMTitles,Publishers_
&WHEREPublishers.PubId=Titles.PubID_
&ANDPublishers.State='CA'
In the same line, comments cannot be added after the line continuation character. There are some restrictions on where line continuation characters can be used.
Combine multiple statements on the same line
Typically, there is one Visual Basic statement on a line without a statement terminator, but you can put two or more statements on the same line by separating them with a colon (:).
Text1.Text=Hello:Red=255:Text1.BackColor=
Red
However, to make it easier to read the code, it's better to put one statement per line.
For more information, see Appendix A, "Visual Basic Specifications, Limitations, and File Format."
Add comments to your code
You will often encounter the comment character (') when reading the examples in this manual. This symbol tells Visual Basic to ignore what follows the symbol. These are comments in the code snippet, both for the convenience of the developer and for the convenience of other programmers who may later examine the source code. For example:
'This is from the left side of the screen
'Start comment.
Text1.Text=Hi! 'Put it in the text box
'Welcome.
Comments can be on the same line as the statement, written after the statement, or they can occupy an entire line. The above code demonstrates both situations. Remember that a comment cannot follow a line continuation character on the same line.
Note You can add or remove comment symbols from a block of code by selecting two or more lines of code and selecting the Comment Block or Remove Comment Block button on the Edit toolbar.
Understand number systems
Most values in this document are in decimal (base 10). But sometimes it is more convenient to use hexadecimal numbers (base 16) or octal numbers (base 8). Visual Basic uses the prefix &H to represent hexadecimal numbers and &O to represent octal numbers. The following table illustrates the decimal, octal, and hexadecimal representation of the same number.
It is usually not necessary to know the hexadecimal or octal number system because computers can work with numbers in either system. However, some number systems are more suitable than others for certain tasks, such as using hexadecimal numbers to set the color of screens and controls.
VisualBasic Naming Conventions
When writing Visual Basic code, you declare and name many elements (Sub and Function procedures, variables, constants, etc.). The names of procedures, variables, and constants declared in Visual Basic code must follow these rules:
1. They must start with a letter.
2. They may not contain embedded periods or type declaration characters (special characters that specify data types).
3. They cannot exceed 255 characters. The names of controls, forms, classes, and modules cannot exceed 40 characters.
4. They cannot have the same name as restricted keywords.
Restricted keywords are words used by Visual Basic and are part of the language. These include predefined statements (such as If and Loop), functions (such as Len and Abs), and operators (such as Or and Mod).
Detailed information For more detailed information about the keyword table, please refer to the "Visual Basic 6.0 Language Reference Manual".
Forms and controls can have the same name as restricted keywords. For example, you can name a control Loop. But the control cannot be referenced in the usual way in the code, because Visual Basic will think that Loop means the keyword. For example, the following code will error.
Loop.Visible=True 'Error.
To reference forms or controls that have the same name as a restricted keyword, you must qualify them or enclose them in square brackets []. For example, the following code will not error.
MyForm.Loop.Visible=True 'Use form name
'Qualify it.
[Loop].Visible=True 'square brackets
'It worked.
Square brackets can be used in this way when referencing forms and controls, but not during variable declaration or procedure definition when the variable or procedure name is the same as the restricted keyword. Square brackets can also be used to force Visual Basic to accept names provided by other type libraries that conflict with restricted keywords.
Note that typing square brackets is tiring, so it is desirable to use less restricted keywords for form or control names. However, if a new version of Visual Basic defines new keywords that conflict with existing forms or controls, you can use this technique when updating your code to use the new version. _
->