Visual Basic (Dont Delete This Fron Ashish)
Visual Basic (Dont Delete This Fron Ashish)
0 Welcome to Microsoft Visual Basic, the fastest and easiest way to create applications for Microsoft Windows. Whether you are an experienced professional or brand new to Windows programming, Visual Basic provides you with a complete set of tools to simplify rapid application development. The "Visual" part refers to the method used to create the graphical user interface (GUI). Rather than writing numerous lines of code to describe the appearance and location of interface elements, you simply add prebuilt objects into place on screen. If you've ever used a drawing program such as Paint, you already have most of the skills necessary to create an effective user interface. The BASIC (Beginners All-Purpose Symbolic Instruction Code) language, a language used by more programmers than any other language in the history of computing. Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions, and keywords, many of which relate directly to the Windows GUI. Beginners can create useful applications by learning just a few of the keywords, yet the power of the language allows professionals to accomplish anything that can be accomplished using any other Windows programming language. There are three main steps to creating an application in Visual Basic: 1. Create the interface. 2. Set properties. 3. Write code.
1.2: A Brief History of Visual Basic A Brief History of Visual Basic Before Visual Basic 1.0 was introduced to the world in 1991, developers had to be well versed in C++ programming, as well as the rudimentary building blocks (Windows API) of the Windows system itself. This complexity meant that only the dedicated and properly trained were capable of turning out software that could run on Windows. Visual Basic changed all of that, and it has been estimated that there are now as many lines of production code written in Visual Basic as in any other language. Visual Basic changed the face of Windows programming by removing the complex burden of writing code for the user interface (UI). By allowing programmers to draw their own UI, it freed them to concentrate on the business problems they were trying to solve. Once the UI is drawn, the programmer can then add code to react to events. Visual Basic has also been extensible from the very beginning. Third-party vendors quickly saw the market for reusable modules to aid developers. These modules, or controls, were original referred to as VBXs (named after their file extension). If you didn't like the way a button behaved you could either buy or create your own. However, these controls had to be written in C or C++. Database access utilities were some of the first controls available. When Microsoft introduced Visual Basic 3.0, the programming world changed again. Now you could build database applications directly accessible to users (so called front-end applications) completely with Visual Basic. There was no need to rely on third-party controls. Microsoft accomplished this task with the introduction of the Data Access Objects (DAO), which allowed programmers to manipulate data with the same ease as manipulating the user interface. Versions 4.0 and 5.0 extended the capabilities of version 3.0 in order to allow developers to target the new Windows 95 platform. Crucially they also made it easier for developers to write code, which could then be manipulated in order to be used by other
language developers. Version 6.0 gave us a new way to access databases with the integration of ActiveX Data Objects (ADO). ADO was developed by Microsoft to aid web developers using Active Server Pages to access databases. With all of the improvements to Visual Basic over the years, it ensured its dominant place in the programming world. It helps developers write robust and maintainable applications in record time.
Chapter 2: Getting Started With Visual Basic 6 This chapter introduces you to the Visual Basic environment and guides you through the creation of your first Visual Basic program. It also presents a number of important concepts that are crucial to Visual Basic programming, such as the event-driven programming model. If you aren't new to Visual Basic, you can probably skip over this chapter without any problem.
Chapter 2.1: The Integrated Development Environment Chapter 2.2: Creating a Simple Application
The Integrated Development Environment Much of the popularity of Visual Basic comes from its Integrated Development Environment, or IDE for short. In theory, you can edit your Visual Basic programs using any editor, including the aged Notepad, but I never met a programmer insane enough to do that. In fact, the IDE gives you everything you need to create great applications, to write code for them, to test and fine-tune them, and, finally, to produce executable files. These files are independent of the environment and therefore can be delivered to customers for execution on their machines, even if they haven't installed Visual Basic.
Chapter 2.1.1: Running the IDE Chapter 2.1.2: Selecting the Project Type Chapter 2.1.3: IDE Windows Chapter 2.1.4: Menus Chapter 2.1.5: Toolbars Chapter 2.1.6: The Toolbox
2.1.1: Running the IDE Running the IDE You can choose from several ways to launch the Visual Basic IDE, as is true for any Windows executable:
You can run the Visual Basic 6 environment from the Start Menu; the exact path to the menu command depends on whether you have installed Visual Basic as part of the Microsoft Visual Studio suite. You can create a shortcut to the IDE on your desktop and run it by simply double-clicking on it. When Visual Basic is installed, it registers the .vbp, .frm, .bas, and a few other extensions with the operating system. Therefore, you can run the environment by double-clicking on any Visual Basic file. If you have installed Microsoft Active Desktop, you can create a shortcut to the Visual Basic IDE on the system taskbar. This is probably the fastest way to run the IDE: it's similar to a desktop shortcut, but you don't have to minimize other windows to uncover it.
Don't underestimate the convenience of running the Visual Basic IDE in the fastest way possible. When you develop COM components or add-ins, you might need to follow the commonplace practice of opening multiple instances of the environment at the same time. You might need to repeat this operation several times during your working day.
2.1.2: Selecting the Project Type Selecting the Project Type The first time you run the Visual Basic IDE, you're asked to select the type of project you want to create, as you can see in below Figure.
In this chapter, as well as in many chapters in this tutorial, we're going to create Standard EXE projects only, so you can click on the Open button or just press the Enter key to start working with a regular project that, once compiled, will deliver a stand-alone EXE
application. You can also decide to tick the "Don't show this dialog in future" check box if you want to avoid this operation the next time you launch the IDE.
2.1.3: IDE Windows IDE Windows If you have worked with Visual Basic 5, the Visual Basic 6 IDE will look very familiar to you, as you can see in this Figure:
In fact, the only indication that you're not interacting with Visual Basic 5 is a couple of new top level menus Query and Diagram and two new icons on the standard toolbar. When you begin to explore the IDE's menus, you might find a few other commands (in the Edit, View, Project, and Tools menus) that were missing in Visual Basic 5. But overall changes are minimal, and if you're familiar with the
Visual Basic 5 environment you can start working with Visual Basic 6 right away. On the other hand, if you have worked only with versions of Visual Basic earlier than 5, you're going to be surprised by the many changes in the working environment. For one thing, the IDE is now an MDI (Multiple Document Interface) application, and you can reduce it and its dependent window with a single operation. You can restore the SDI (Single Document Interface) working mode, if you prefer, by choosing Options from the Tools menu, clicking the Advanced tab, and ticking the SDI Development Environment check box. Finally, if this is your first exposure to Visual Basic, you'll surely be confused by the many menu commands, toolbars, and windows that the IDE hosts. Let's quickly review the purpose of each item. You can display any of the windows using an appropriate command in the View menu. Many of them can also be opened using a keyboard shortcut, as described in the following paragraphs, or by clicking on an icon in the main toolbar.
The Project window gives you an overview of all the modules that are contained in your application. You can display such modules grouped by their types or in alphabetical order by clicking on the rightmost icon on the Project window's toolbar. You can then view the code in each module or the object associated with each module (for example, a form) by clicking the first or the second icon, respectively. You can quickly display the Project window or put it in front of other windows by pressing the Ctrl+R key combination or by clicking on the Project Explorer icon on the standard toolbar. You use the Form Designer window to design your application's user interface. Any application can contain multiple forms, and you can open a number of form designers at the same time. Moreover, both Visual Basic 5 and 6 support additional designers, such as the UserControl and UserDocument designers. The Toolbox window includes a set of objects that you can place on a form or on another designer. Visual Basic comes
with a fixed set of controls the so-called intrinsic controls but you can add other Microsoft ActiveX controls to this window. To avoid filling this window with too many controls, you can create multiple tabs on it: just right-click on the window, select the Add Tab command, and at a prompt assign a name to the new tab. Then you can place additional ActiveX controls on this new tab or drag one or more controls from the General tab. Similarly, you can delete or rename any tab by right-clicking on it and selecting the Delete Tab or Rename Tab commands, respectively. You can't delete or rename the General tab, though. You use the Code window to write code that determines the behavior of your forms and other objects in your application. You can keep a number of code windows visible at one time, each one displaying the code related to a form or, more generally, to a module in your application. You can't open two code windows for the same module; however, you can split a code window into two distinct and independent portions by dragging the small gray rectangle located immediately above the vertical scrollbar. The Properties window lists all the properties of the object that's currently selected and gives you the opportunity to modify them. For instance, you can change the foreground and background colors of the form or the control that's currently selected. You can list properties in alphabetical order or group them in categories, and you can find a short description of the currently selected property near the bottom of this window. When you select an object, its properties are automatically displayed in the Properties window. If the window isn't visible, you can quickly display it by pressing the F4 key or by clicking on the Toolbox icon on the toolbar. The Color Palette window is handy for quickly assigning a color to an object, such as the control that's currently selected on a form designer. You can select the foreground color of an object by left-clicking on the desired color, and if you click on an empty item in the bottom row of cells you can also define a custom color. Finally, you can select the background color of
an object if you click on the larger square located near the upper left corner of the Color Palette window. The Form Layout window shows how a given form will be displayed when the program runs. You can drag a form to the place on the screen where you want it to appear during execution, and you can also compare the relative sizes and positions of two or more forms. By right-clicking on this window, you can show its resolution guides, which enable you to check how your forms display at screen resolutions different from the current one. The Immediate window lets you enter a Visual Basic command or expression and see its result using the Print command (which can also be shortened to ?). In break mode that is, when you have temporarily suspended a running program you can use these commands to display the current value of a variable or an expression. You can also write diagnostic messages from your application's code to this window using the Debug.Print statement. Because the Immediate window isn't visible when the application is compiled and executed outside the environment, such diagnostic statements aren't included in the executable file. You can quickly open the Immediate window by pressing the Ctrl+G key combination. The Object Browser is one of the most important tools available to the Visual Basic developer. It lets you explore external libraries so that you can learn about the objects they expose and their properties, methods, and events. The Object Browser also helps you quickly locate and jump to any procedure in any module of your application. You can open the Object Browser by pressing the F2 key or by clicking its icon on the standard toolbar. The Locals window is active only when a program is executing. It lists the values of all the variables that are local to a module or to a procedure. If the variable is an object itself (a form or a control, for example) a plus (+) sign appears to the left of the variable name, which means that you can expand it and look at its properties. The Watches window has a dual purpose: it lets you continuously monitor the value of a variable or an expression
in your program including a global variable, which is outside the capabilities of the Locals window and it also gives you the ability to stop the execution of a program when a given expression becomes True or whenever it changes its value. You can add one or more watch expressions using the Add Watch command from the Debug menu, or you can select the Add Watch command from the pop-up menu that appears when you right-click the Watches window itself. The Call Stack window appears only when you break the execution of a running program and press Ctrl+L. It shows all the procedures that are waiting for the current procedure to complete. It's a useful debugging tool in that it lets you understand the execution path that led to the current situation. Note that this is a modal window, so you must close it to resume regular execution. The Data View window is new to Visual Basic. In a nutshell, the Data View window offers an integrated tool to administer your databases and to explore their structures and the attributes of their tables and fields. The Data View window is particularly versatile when connecting to a Microsoft SQL Server or Oracle database because you can also add and delete its tables, views, and fields and edit stored procedures. Regardless of the database you're using, you can often drag tables and fields from the Data View window onto other windows in the IDE. You display this window using the Data View command from the View menu or by clicking on its icon on the standard toolbar.
Most of the windows I've just described can be docked: in other words, they can stick to the external frame of the main window of the IDE and are always on top of all other windows. By default, the majority of IDE windows are docked, although only the Toolbox, Project, Properties, and Form Layout windows are visible when the environment is launched. You can switch the Docked attribute on and off for a single window by right-clicking in it and then selecting the Dockable menu command. Alternatively, you can modify the
Docked attribute individually for all the windows in the IDE by choosing Options from the Tools menu and then clicking the Docking tab. Just tick the check box associated with any window you want to be docked.
2.1.4: Menus Menus It's unnecessary to describe in detail the purpose of each menu command at this point in the tutorial because most of the commands are related to advanced features of Visual Basic. But I think that an overview of all the top-level menus is useful, in that it gives you an idea of where to look for a given function when you need it.
The File menu includes the commands to load and save a Visual Basic project or a group of projects (Visual Basic 6 can open multiple projects in the environment), to save the current module, to print the entire project or selected portions of it, and to build the executable file. The Edit menu lets you perform the typical editing commands, including Cut, Copy, Paste, Find, Replace, Undo, and Redo. It also includes commands that act on database tables, but they are active only when you're viewing the structure of a database or a database diagram. This menu also includes a bunch of commands related to Microsoft IntelliSense, a feature of the Visual Basic IDE that lets you automatically complete commands, list the syntax of functions and expected arguments, and so forth. The View menu is the primary means of displaying any of the environment's windows described previously. It also includes some database-related commands that are enabled only if you have activated a tool for database maintenance. The Project menu lets you add modules to the current project, including forms, standard (BAS) modules, class modules, UserControl modules, and so on. It also lets you add designer modules, which are the key to many new Visual Basic 6
features. The last three commands in this menu are particularly useful because they give you access to the References, the Components, and the Project Properties dialog boxes, respectively. The Format menu is used to align and resize one or more controls on a form or on a designer of any type. You can also center a control on its form and increase or decrease the distance among a group of controls. When you're satisfied with the appearance of your form, you should select the Lock Controls option so that you can't accidentally move or resize the controls using the mouse. The Debug menu contains the commands that you usually issue when you're testing an application within the IDE. You can execute your code step-by-step, display the value of a variable or an expression, and set one or more breakpoints in code. Breakpoints are special points in the code that, when reached during the program's execution, cause the Visual Basic environment to interrupt execution, thus entering break mode. You can also create conditional breakpoints, which are expressions that are monitored as each statement is executed. When the value of a conditional breakpoint changes or when the condition you specified becomes True, the program enters break mode and you can debug it easily. The Run menu is probably the simplest of the group. It contains the commands to start the execution of the application being developed, to stop it and enter break mode, and to definitively end it. The Query menu is new to the Visual Basic environment. It's available only in Visual Basic Enterprise and Professional Editions and only when you're interactively creating an SQL query using the Microsoft Query Builder utility, which you can see in below Figure:
The Diagram menu, shown in below Figure, is also new to Visual Basic. As with the Query menu, the Diagram menu is available only in the Enterprise and Professional Editions and only when you're interacting with SQL Server or Oracle databases to create or edit a database diagram.
The Tools menu contains several miscellaneous commands, the most important of which is the Options command. This command allows you to access a dialog box that lets you customize the IDE.
The Add-In menu lists a collection of commands related to external modules that integrate into the environment. Visual Basic 6 itself comes with a number of such external add-ins, and you can also write your own. The Window menu is the typical menu that you find in most MDI applications; it lets you arrange and tile your windows. The Help menu is also standard for Microsoft Windows applications. Visual Basic 6 doesn't use standard HLP files any longer, and its help subsystem requires that you install Microsoft Developer Network (MSDN) to access its documentation.
2.1.5: Toolbars Toolbars Visual Basic comes with a standard toolbar that includes many common commands, such as those for loading and saving the project, running the program, and opening the most frequently used windows. Three more toolbars, Debug, Edit, and Form Editor, are visible only after you right-click on the standard toolbar and select one toolbar at a time from the submenu that appears. You can also make these toolbars visible by selecting the Toolbars option from the View menu. All the toolbars can be docked in the upper portion of the main IDE window, or they can freely float in the environment, as you can see in below Figure.
You can quickly dock a floating toolbar by double-clicking on its title bar, and you can make a docked toolbar float by double-clicking on its left-most vertical stripes. If you want to know what a particular toolbar icon represents, place the mouse cursor over it and a yellow ToolTip showing a short explanation will appear after about a second. The Debug toolbar hosts most of the commands that are found in the Debug menu. The Edit toolbar is useful when you're editing code and setting breakpoints and bookmarks. The Form Editor toolbar includes most of the commands in the Format menu and is useful only when you're arranging controls on a form's surface. Making these additional toolbars visible or not is largely a matter of personal taste. I usually prefer not to waste valuable desktop space with toolbars other than the standard one. If you work with a higher screen resolution, this might not be an issue for you. You can customize the appearance of all the Visual Basic toolbars and even create new ones, as you can see in below Figure.
The procedure for creating a new toolbar is simple: 1. Right-click on any toolbar, and select the Customize menu command; this brings up the Customize dialog box. 2. Click the New button, and type a name for the new custom toolbar (for example, Custom Toolbar). The name of the new toolbar appears in the list of toolbars, and its check box is ticked. The empty toolbar appears on the screen. You're now ready to add commands to it. 3. Click the Commands tab, and then click a menu name in the leftmost list box. Click on an item in the list box on the right, and drag it over the custom toolbar to the spot where you want to insert it. 4. Right-click on the icon you have just added, and select a command from the pop-up menu that appears. The commands in this menu let you replace the icon with a different one, associate it with a caption, make it the beginning of a group, and so on. 5. Repeat steps 3 and 4 for all the commands you want to add to the custom toolbar, and then click on the Close button to make your additions permanent.
Here are a few commands that you should consider for inclusion in a custom toolbar because they're frequently used but don't have any associated hot keys:
The References and Properties commands from the Project menu The Comment Block and Uncomment Block commands from the Edit toolbar (not displayed on the menu) All the Bookmark submenu commands from the Edit menu The Options command from the Tools menu
2.1.6: The Toolbox The Toolbox The Toolbox window is probably the first window you'll become familiar with because it lets you visually create the user interface for your applications. More specifically, the Toolbox contains the icons of all the intrinsic controls that is, all the controls that are included in the Visual Basic runtime. If you have already programmed with a previous version of Visual Basic, you surely know the characteristics of all the controls that are present in the Toolbox. If you haven't, refer to below Figure while you read the following condensed descriptions.
The Pointer isn't a control; click this icon when you want to select controls already on the form rather than create new ones. The PictureBox control is used to display images in any of the following formats: BMP, DIB (bitmap), ICO (icon), CUR
(cursor), WMF (metafile), EMF (enhanced metafile), GIF, and JPEG. The Label control serves to display static text or text that shouldn't be edited by the user; it's often used to label other controls, such as TextBox controls. The TextBox control is a field that contains a string of characters that can be edited by the user. It can be single-line (for entering simple values) or multiline (for memos and longer notes). This is probably the most widely used control of any Windows application and is also one of the richest controls in terms of properties and events. The Frame control is typically used as a container for other controls. You rarely write code that reacts to events raised by this control. The CommandButton control is present in almost every form, often in the guise of the OK and Cancel buttons. You usually write code in the Click event procedure of this control. The CheckBox control is used when the user has to make a yes/no, true/false selection. OptionButton controls are always used in groups, and you can select only one control in the group at a time. When the user selects a control in the group, all other controls in the group are automatically deselected. OptionButton controls are useful for offering to the user a number of mutually exclusive selections. If you want to create two or more groups of OptionButton controls on a form, you must place each group inside another container control (most often a Frame control). Otherwise, Visual Basic can't understand which control belongs to which group. The ListBox control contains a number of items, and the user can select one or more of them (depending on the value of the control's MultiSelect property). The ComboBox control is a combination of a TextBox and a ListBox control, with the difference that the list portion is visible only if the user clicks on the down arrow to the right of the edit area. ComboBox controls don't support multiple selections. The HScrollBar and VScrollBar controls let you create standalone scroll bars. These controls are used infrequently because
the majority of other controls display their own scroll bars if necessary. Stand-alone scroll bars are sometimes used as sliders, but in this case you'd better use other, more eyecatching controls, such as the Slider control. The Timer control is peculiar in that it isn't visible at run time. Its only purpose is to regularly raise an event in its parent form. By writing code in the corresponding event procedure, you can perform a task in the background for instance, updating a clock or checking the status of a peripheral device. The DriveListBox, DirListBox, and FileListBox controls are often used together to create file-oriented dialog boxes. DriveListBox is a ComboBox-like control filled automatically with the names of all the drives in the system. DirListBox is a variant of the ListBox control; it shows all the subdirectories of a given directory. FileListBox is another special ListBox control; this control fills automatically with names of the files in a specified directory. While these three controls offer a lot of functionality, in a sense they have been superseded by the Common Dialog control, which displays a more modern user interface. If you want to write applications that closely conform to the Windows 9x look, you should avoid using these controls. The Shape and Line controls are mostly cosmetic controls that never raise any events and are used only to display lines, rectangles, circles, and ovals on forms or on other designers. The Image control is similar to the PictureBox control, but it can't act as a container for other controls and has other limitations as well. Nevertheless, you should use an Image control in place of a PictureBox control whenever possible because Image controls consume fewer system resources. The Data control is the key to data binding, a Visual Basic feature that lets you connect one or more controls on a form to fields in a database table. The Data control works with Jet databases even though you can also use attached tables to connect to data stored in databases stored in other formats. But it can't work with ActiveX Data Objects (ADO) sources and is therefore not suitable for exploiting the most interesting database-oriented Visual Basic 6 features. The OLE control can host windows belonging to external programs, such as a spreadsheet window generated by
Microsoft Excel. In other words, you can make a window provided by another program appear as if it belongs to your Visual Basic application.
From this short description, you can see that not all the intrinsic controls are equally important. Some controls, such as the TextBox, Label, and CommandButton controls, are used in virtually every Visual Basic application, while other controls, such as the DriveListBox, DirListBox, and FileListBox controls, have been replaced, in practice, by newer controls. Similarly, you shouldn't use the Data control in any application that uses the ADO data sources.
2.2: Creating a Simple Application Creating a Simple Application Visual Basic lets you build a complete and functional Windows application by dropping a bunch of controls on a form and writing some code that executes when something happens to those controls or to the form itself. For instance, you can write code that executes when a form loads or unloads or when the user resizes it. Likewise, you can write code that executes when the user clicks on a control or types while the control has the input focus. This programming paradigm is also known as event driven programming because your application is made up of several event procedures executed in an order that's dependent on what happens at run time. The order of execution can't, in general, be foreseen when the program is under construction. This programming model contrasts with the procedural approach, which was dominant in the old days. This section offers a quick review of the event-driven model and uses a sample application as a context for introducing Visual Basic's intrinsic controls, with their properties, methods, and events. This sample application, a very simple one, queries the user for the lengths of the two sides of a rectangle, evaluates its perimeter and area, and displays the results to the user.
Chapter 2.2.1: Adding Controls to a Form Chapter 2.2.2: Setting Properties of Controls Chapter 2.2.3: Naming Controls Chapter 2.2.4: Moving and Resizing
Controls Chapter 2.2.5: Setting the Tab Order Chapter 2.2.6: Adding Code Chapter 2.2.7: Running and Debugging the Program Chapter 2.2.8: Refining the Sample Program Chapter 2.2.9: Ready, Compile, Run!
2.2.1: Adding Controls to a Form Adding Controls to a Form We're ready to get practical. Launch the Visual Basic IDE, and select a Standard EXE project. You should have a blank form near the center of the work area. More accurately, you have a form designer, which you use to define the appearance of the main window of your application. You can also create other forms, if you need them, and you can create other objects as well, using different designers (the UserControl and UserDocument designers, for example). Other chapters of this tutorial are devoted to such designers. One of the greatest strengths of the Visual Basic language is that programmers can design an application and then test it without leaving the environment. But you should be aware that designing and testing a program are two completely different tasks. At design time, you create your forms and other visible objects, set their properties, and write code in their event procedures. Conversely, at run time you monitor the effects of your programming efforts: What you see on your screen is, more or less, what your end users will see. At run time, you can't invoke the form designer, and you have only a limited ability to modify the code you have written at design time. For instance, you can modify existing statements and add new ones, but you can't add new procedures, forms, or controls. On the other hand, at run time you can use some diagnostic tools that
aren't available at design time because they would make no sense in that context (for example, the Locals, the Watches, and the Call Stack windows). To create one or more controls on a form's surface, you select the control type that you want from the Toolbox window, click on the form, and drag the mouse cursor until the control has the size and shape you want. (Not all controls are resizable. Some, such as the Timer control, will allow you to drag but will return to their original size and shape when you release the mouse button.) Alternatively, you can place a control on the form's surface by double-clicking its icon in the Toolbox: this action creates a control in the center of the form. Regardless of the method you follow, you can then move and resize the control on the form using the mouse. To complete our Rectangle sample application, we need four TextBox controls two for entering the rectangle's width and height and two for showing the resulting perimeter and area. Even if they aren't strictly required from an operational point of view, we also need four Label controls for clarifying the purpose of each TextBox control. Finally we add a CommandButton control named Evaluate that starts the computation and shows the results. Place these controls on the form, and then move and resize them as depicted in this Figure:
Don't worry too much if the controls aren't perfectly aligned because you can later move and resize them using the mouse or using the commands in the Format menu.
2.2.2: Setting Properties of Controls Setting Properties of Controls Each control is characterized by a set of properties that define its behavior and appearance. For instance, Label controls expose a Caption property that corresponds to the character string displayed on the control itself, and a BorderStyle property that affects the appearance of a border around the label. The TextBox control's most important property is Text, which corresponds to the string of characters that appears within the control itself and that can be edited by the user. In all cases, you can modify one or more properties of a control by selecting the control in the form designer and then pressing F4 to show the Properties window. You can scroll through the contents of the Properties window until the property you're interested in becomes visible. You can then select it and enter a new value. Using this procedure, you can modify the Caption property of all four Label controls to &Width, &Height, &Perimeter, and &Area, respectively. You will note that the ampersand character doesn't appear on the control and that its effect is to underline the character that follows it. This operation actually creates a hot key and associates it with the control. When a control is associated with a hot key, the user can quickly move the focus to the control by pressing an Alt+x key combination, as you normally do within most Windows applications. Notice that only controls exposing a Caption property can be associated with a hot key. Such controls include the Label, Frame, CommandButton, OptionButton, and CheckBox. Notice that once you have selected the Caption property for the first Label control, it stays selected when you then click on other controls. You can take advantage of this mechanism to change the Caption property of the CommandButton control to &Evaluate and the Caption property of the Form itself to Rectangle Demo, without having to select the Caption item in the Properties window each time. Note that ampersand characters within a form's caption don't have any special meaning.
As an exercise, let's change the font attributes used for the controls, which you do through the Font property. While you can perform this action on a control-by-control basis, it's much easier to select the group of controls that you want to affect and then modify their properties in a single operation. To select multiple controls, you can click on each one of them while you press either the Shift or the Ctrl key, or you can drag an imaginary rectangle around them. (This technique is also called lassoing the controls.) When you select a group of controls and then press the F4 key, the Properties window displays only the properties that are common to all the selected controls. The only properties that are exposed by any control are Left, Top, Width, and Height. If you select a group of controls that display a string of characters, such as the TextBox, Label, and CommandButton controls in our Rectangle example, the Font property is also available and can therefore be selected. When you double-click on the Font item in the Properties window, a Font dialog box appears. Let's select a Tahoma font and set its size to 11 points. Finally we must clear the Text property of each of the four TextBox controls so that the end user will find them empty when the program begins its execution. Oddly, when you select two or more TextBox controls, the Text property doesn't appear in the Properties window. Therefore, you must set the Text property to an empty string for each individual TextBox control on the form. To be honest, I don't know why this property is an exception to the rule stated earlier. The result of all these operations is shown in below Figure:
Naming Controls One property that every control has and that's very important to Visual Basic programmers is the Name property. This is the string of characters that identifies the control in code. This property can't be an empty string, and you can't have two or more controls on a form with the same name. The special nature of this property is indirectly confirmed by the fact that it appears as (Name) in the Properties window, where the initial parenthesis serves to move it to the beginning of the property list. When you create a control, Visual Basic assigns it a default name. For example, the first TextBox control that you place on the form is named Text1, the second one is named Text2, and so forth. Similarly, the first Label control is named Label1, and the first CommandButton control is named Command1. This default naming scheme frees you from having to invent a new, unique name each time you create a control. Notice that the Caption property of Label and CommandButton controls, as well as the Text property of TextBox controls, initially reflect the control's Name property, but the two properties are independent of each other. In fact, you have just modified the Caption and Text properties of the controls in the Rectangle Demo form without affecting their Name properties. Because the Name property identifies the control in code, it's a good habit to modify it so that it conveys the meaning of the control itself. This is as important as selecting meaningful names for your variables. In a sense, most controls on a form are special variables whose contents are entered directly by the user. Microsoft suggests that you always use the same three-letter prefix for all the controls of a given class. The control classes and their recommended prefixes are shown in below Table:
Control Class CommandButton TextBox Label PictureBox Prefix cmd txt lbl pic Control Class Data HScrollBar VScrollBar DriveListBox Prefix dat hsb vsb drv
For instance, you should prefix the name of a TextBox control with txt, the name of a Label control with lbl, and the name of a CommandButton control with cmd. Forms should also follow this convention, and the name of a form should be prefixed with the frm string. This convention makes a lot of sense because it lets you deduce both the control's type and meaning from its name. This tutorial sticks to this naming convention, especially for more complex examples when code readability is at stake. In our example, we will rename the Text1 through Text4 controls as txtWidth, txtHeight, txtPerimeter, and txtArea respectively. The Command1 control will be renamed cmdEvaluate, and the four Label1 through Label4 controls will be renamed lblWidth, lblHeight, lblPerimeter, and lblArea, respectively. However, please note that Label controls are seldom referred to in code, so in most cases you can leave their names unmodified without affecting the code's readability.
2.2.4: Moving and Resizing Controls Moving and Resizing Controls You probably won't be able to place your controls on the form in the right position on your first attempt. Most likely, you will try several layouts until you are satisfied with the overall appearance of the form. Fortunately, the IDE offers you many ways to modify the position and size of your controls without much effort.
Select one or more controls, and move them as a single entity using the mouse.
Move one or more controls with arrow keys while you press the Ctrl key. The steps along the x- and y-axes are determined by the Grid Units settings. You can view and modify these settings using the General tab of the Options dialog box from the Tools menu. Resize the selected control(s) by using the arrow keys while you press the Shift key. You can also resize a control by dragging one of the blue handles surrounding it when it is selected. Like the move operation, the resize step depends on the Grid Units settings. Center a control or a group of controls on the form, either horizontally or vertically, using the Center In Form submenu of the Format menu. Align a group of controls with respect to another control using the commands in the Align submenu of the Format menu. The control used as a reference in the aligning process is the one that was selected last (that is, the one with blue handles around it). Resize a group of controls by selecting them and invoking a command in the Make Same Size submenu of the Format menu. All selected controls will be resized to reflect the size of the control that was selected last. You can align or resize a group of controls by selecting them, pressing F4 to display the Properties window, and then manually modifying the Left, Top, Width, or Height properties. This procedure is useful when you know the absolute position or size of the controls.
2.2.5: Setting the Tab Order Setting the Tab Order Windows standards dictate that the user can press the Tab key to visit all the fields in a window in the logical order. Such a sequence is known as the Tab order sequence. In Visual Basic, you set the correct Tab order sequence by assigning a proper value to the TabIndex property for all the controls that can receive the input
focus, starting with 0 for the control that should receive the input focus when the form appears and assigning increasing values for all the others. In our Rectangle sample application, this means assigning 0 to the txtWidth control's TabIndex property, 1 to the txtHeight control's TabIndex property, and so on. But wait, there's more to know about the Tab order setting. Even if Label controls never get the focus themselves, they expose a TabIndex property. Why? As I mentioned previously, TextBox controls or more to the point, controls that don't expose a Caption property can't be directly associated with a hot key. This means that you can't use an Alt+x key combination to activate them. In our Rectangle example, we overcome this limitation by placing Label controls above each individual TextBox control. Unfortunately, placing a Label control near another control doesn't automatically provide it with hot key capabilities. To have a Label control lend its hot key to another control on the form, you must assign the Label's TabIndex property a value that is 1 less than the value of the other control's TabIndex property. In our Rectangle sample application, this means assigning the TabIndex property as follows: 0 to lblWidth, 1 to txtWidth, 2 to lblHeight, 3 to txtHeight, 4 to cmdEvaluate, 5 to lblPerimeter, 6 to txtPerimeter, 7 to lblArea, and 8 to txtArea. It's immediately apparent that when you have forms with tens or even hundreds of controls, correctly setting the TabIndex property for each one of them is a nuisance. For this reason, a number of third-party commercial or shareware vendors have developed special add-ins that permit you to solve this task in a visual manner, for example by clicking on each control, or in a semiautomatic manner by analyzing the relative position of all controls on the form. While these add-ins are real lifesavers, here's a trick well known among Visual Basic programmers that solves the problem with relatively little effort: 1. Select the last control in your planned Tab order.
2. Press the Ctrl+Shift+T key combination to activate the Properties window. For most controls, this combination selects the TabIndex properties; for others, you might need to press it more than once. 3. Press the 0 key, thus assigning a 0 to the TabIndex property of the selected control. 4. Click on the next to last control in the Tab order, and press the 0 key again; this assigns a 0 to the TabIndex property of the current control and 1 to the TabIndex property of the last control. This occurs because Visual Basic prevents you from using the same TabIndex value for two or more controls on the same form. 5. Repeat step 4, working backward in the Tab order sequence and pressing the 0 key after selecting each control. When you reach the first control in the sequence, the TabIndex property for all the controls on the form will be set correctly.
Now that we have completed our project, we'll save it. Choose Save Project from the File menu, or click the floppy disk icon. Visual Basic will ask you for the name of the form file, and again for the name of the project file; type Rectangle for both. You'll see that you now have two new files, Rectangle.frm and Rectangle.vbp.
2.2.6: Adding Code Adding Code Up to this point, you have created and refined the user interface of your program and created an application that in principle can be run. (Press F5 and run it to convince yourself that it indeed works.) But you don't have a useful application yet. To turn your pretty but useless program into your first working application, you need to add some code. More precisely, you have to add some code in the Click event of the cmdEvaluate control. This event fires when the user clicks on the Evaluate button or presses its associated hot key (the Alt+E key combination, in this case).
To write code within the Click event, you just select the cmdEvaluate control and then press the F7 key, or right-click on it and then invoke the View Code command from the pop-up menu. Or you simply double-click on the control using the left mouse button. In all cases, the code editor window appears, with the flashing cursor located between the following two lines of code:
Private Sub cmdEvaluate_Click()
End Sub
Visual Basic has prepared the template of the Click event procedure for you, and you have to add one or more lines of code between the Sub and End Sub statements. In this simple program, you need to extract the values stored in the txtWidth and txtHeight controls, use them to compute the rectangle's perimeter and area, and assign the results to the txtPerimeter and txtArea controls respectively:
Private Sub cmdEvaluate_Click() ' Declare two floating point variables. Dim reWidth As Double, reHeight As Double ' Extract values from input TextBox controls. reWidth = CDbl(txtWidth.Text) reHeight = CDbl(txtHeight.Text) ' Evaluate results and assign to output text boxes. txtPerimeter.Text = CStr((reWidth + reHeight) * 2) txtArea.Text = CStr(reWidth * reHeight) End Sub
Note that you should always use the Dim statement to declare the variables you are going to use so that you can specify for them the most suitable data type. If you don't do that, Visual Basic will default them to the Variant data type. While this would be OK for this sample program, for most occasions you can make better and faster applications if you use variables of a more specific type. Moreover, you should add an Option Explicit statement at the very beginning of the code module so that Visual Basic will automatically trap any attempt to use a variable that isn't declared anywhere in
the program code. By this single action, you'll avoid a lot of problems later in the development phase.
2.2.7: Running and Debugging the Program Running and Debugging the Program You're finally ready to run this sample program. You can start its execution in several ways: By invoking the Start command from the Run menu, by clicking the corresponding icon on the toolbar, or by pressing the F5 key. In all cases, you'll see the form designer disappear and be replaced (but not necessarily in the same position on the screen) by the real form. You can enter any value in the leftmost TextBox controls and then click on the Evaluate button (or press the Alt+E key combination) to see the calculated perimeter and area in the rightmost controls. When you're finished, end the program by closing its main (and only) form. This program is so simple that you hardly need to test and debug it. Of course, this wouldn't be true for any real-world application. Virtually all programs need to be tested and debugged, which is probably the most delicate (and often tedious) part of a programmer's job. Visual Basic can't save you from this nuisance, but at least it offers so many tools that you can often complete it very quickly. To see some Visual Basic debugging tools in action, place a breakpoint on the first line of the Click event procedure while the program is in design mode. You can set a breakpoint by moving the text cursor to the appropriate line and then invoking the Toggle Breakpoint command from the Debug menu or pressing the F9 shortcut key. You can also set and delete breakpoints by leftclicking on the gray vertical strip that runs near the left border of the code editor window. In all cases, the line on which the breakpoint is set will be highlighted in red. After setting the breakpoint at the beginning of the Click event procedure, press F5 to run the program once again, enter some
values in the Width and Height fields, and then click on the Evaluate button. You'll see the Visual Basic environment enter break mode, and you are free to perform several actions that let you better understand what's actually going on:
Press F8 to execute the program one statement at a time. The Visual Basic instruction that's going to be executed next that is, the current statement is highlighted in yellow. Show the value of an expression by highlighting it in the code window and then pressing F9 (or selecting the Quick Watch command from the Debug menu). You can also add the selected expression to the list of values displayed in the Watch window, as you can see in this Figure:
An alternative way to show the value of a variable or a property is to move the mouse cursor over it in the code window; after a couple of seconds, a yellow data tip containing the corresponding value appears. Evaluate any expression by clicking on the Immediate window and typing ? or Print followed by the expression. This is necessary when you need to evaluate the value of an expression that doesn't appear in the code window. You can view the values of all the local variables (but not expressions) by selecting the Locals command from the View menu. This command is particularly useful when you need to
monitor the value of many local variables and you don't want to set up a watching expression for each one. You can affect the execution flow by placing the text cursor on the statement that you want to execute next and then selecting the Set Next Statement command from the Debug menu. Or you can press the Ctrl+F9 key combination. You need this technique to skip over a piece of code that you don't want to execute or to reexecute a given block of lines without restarting the program.
2.2.8: Refining the Sample Program Refining the Sample Program Our first Visual Basic project, Rectangle.vbp, is just a sample program, but this is no excuse not to refine it and turn it into a complete and robust, albeit trivial, application. The first type of refinement is very simple. Because the txtPerimeter and txtArea controls are used to show the results of the computation, it doesn't make sense to make their contents editable by the user. You can make them read-only fields by setting their Locked property to True. (A suggestion: select the two controls, press F4, and modify the property just once.) Some programmers prefer to use Label controls to display result values on a form, but using read-only TextBox controls has an advantage: The end user can copy their contents to the clipboard and paste those contents into another application. A second refinement is geared toward increasing the application's consistency and usability. Let's suppose that your user uses the Rectangle program to determine the perimeter and area of a rectangle, takes note of the results, and then enters a new width or a new height (or both). Unfortunately, an instant before your user clicks on the Evaluate button the phone rings, engaging the user in a long conversation. When he or she hangs up, the form shows a plausible, though incorrect, result. How can you be sure that those values won't be mistaken for good ones? The solution is simple,
indeed: as soon as the user modifies either the txtWidth or the txtHeight TextBox controls, the result fields must be cleared. In Visual Basic, you can accomplish this task by trapping each source control's Change event and writing a couple of statements in the corresponding event procedure. Since Change is the default event for TextBox controls just as the Click event is for CommandButtons controls you only have to double-click the txtWidth and txtHeight controls on the form designer to have Visual Basic create the template for the corresponding event procedures. This is the code that you have to add to the procedures:
Private Sub txtWidth_Change() txtPerimeter.Text = "" txtArea.Text = "" End Sub
Note that you don't have to retype the statements in the txtHeight's Change event procedure: just double-click the control to create the Sub ... End Sub template, and then copy and paste the code from the txtWidth_Click procedure. When you're finished, press F5 to run the program to check that it now behaves as expected. The purpose of the next refinement that I am proposing is to increase the program's robustness. To see what I mean, run the Rectangle project and press the Evaluate button without entering width or height values: the program raises a Type Mismatch error when trying to extract a numeric value from the txtWidth control. If this were a real-world, compiled application, such an untrapped error would cause the application to end abruptly, which is, of course, unacceptable. All errors should be trapped and dealt with in a convenient way. For example, you should show the user where the problem is and how to fix it. The easiest way to achieve this is by setting up an error handler in the cmdEvaluate_Click procedure, as follows. (The lines you would add are in boldface.)
Private Sub cmdEvaluate_Click() ' Declare two floating point variables. Dim reWidth As Double, reHeight As Double On Error GoTo WrongValues
' Extract values from input textbox controls. reWidth = CDbl(txtWidth.Text) reHeight = CDbl(txtHeight.Text) Ensure that they are positive values. If reWidth <= 0 Or reHeight <= 0 Then GoTo WrongValues ' Evaluate results and assign to output text boxes. txtPerimeter.Text = CStr((reWidth + reHeight) * 2) txtArea.Text = CStr(reWidth * reHeight) Exit Sub WrongValues: MsgBox "Please enter valid Width and Height values", vbExclamation
End Sub
Note that we have to add an Exit Sub statement to prevent the MsgBox statement from being erroneously executed during the normal execution flow. To see how the On Error statement works, set a breakpoint on the first line of this procedure, run the application, and press the F8 key to see what happens when either of the TextBox controls contains an empty or invalid string.
2.2.9: Ready, Compile, Run! Ready, Compile, Run! Visual Basic is a very productive programming language because it allows you to build and test your applications in a controlled environment, without first producing a compiled executable program. This is possible because Visual Basic converts your source code into p-code and then interprets it. P-code is a sort of intermediate language, which, because it's not executed directly by the CPU, is slower than real natively compiled code. On the other hand, the conversion from source code to p-code takes only a
fraction of the time needed to deliver a compiled application. This is a great productivity bonus unknown to many other languages. Another benefit of p-code is that you can execute it step-by-step while the program is running in the environment, investigate the values of the variables, and to some extent even modify the code itself. This is a capability that many other languages don't have or have acquired only recently; for example, the latest version of Microsoft Visual C++ has it. By comparison, Visual Basic has always offered this feature, which undoubtedly contributed to making it a successful language. At some time during the program development, you might want to create an executable (EXE) program. There are several reasons to do this: compiled programs are often (much) faster than interpreted ones, users don't need to install Visual Basic to run your application, and you usually don't want to let other people peek at your source code. Visual Basic makes the compilation process a breeze: when you're sure that your application is completed, you just have to run the Make projectname command from the File menu. It takes a few seconds to create the Rectangle.exe file. This executable file is independent of the Visual Basic environment and can be executed in the same way as any other Windows application for example, from the Run command of the Start menu. But this doesn't mean that you can pass this EXE file to another user and expect that it works. All Visual Basic programs, in fact, depend on a number of ancillary files most notably the MSVBVM60.DLL file, a part of the Visual Basic runtime and won't execute accurately unless all such files are correctly installed on the target system. For this reason, you should never assume that a Visual Basic program will execute on every Windows system because it's working on your computer or on other computers in your office. (If your business is software development, it's highly probable that the Visual Basic environment is installed on all the computers around you.) Instead, prepare a standard installation using the Package and Deployment Wizard, and try running your application on a clean system. If you develop software professionally, you should always have such a clean system at hand, if possible with just the
operating system installed. If you're an independent developer, you probably won't be inclined to buy a complete system just to test your software. I found a very simple and relatively inexpensive solution to this dilemma: I use one computer with removable hard disks, so I can easily test my applications under different system configurations. And since a clean system requires only hundreds of megabytes of disk space, I can recycle all of my old hard disks that aren't large enough for any other use. Before I conclude this chapter, you should be aware of one more detail. The compilation process doesn't necessarily mean that you aren't using p-code. In the Visual Basic jargon, compiling merely means creating an executable file. In fact, you can compile to pcode, even if this sounds like an oxymoron to a developer coming from another language.
In this case, Visual Basic creates an EXE file that embeds the same p-code that was used inside the development environment. That's why you can often hear Visual Basic developers talking about pcode and native-code compilations to better specify which type of compilation they're referring to.
In general, such p-code-compiled programs run at the same speed as interpreted programs within the IDE, so you're missing one of the biggest benefits of the compilation process. But here are a few reasons why you might decide to create a p-code executable:
P-code-compiled executables are often smaller than programs compiled to native code. This point can be important if you're going to distribute your application over the Internet or when you're creating ActiveX controls that are embedded in an HTML page. P-code compilation is often faster than native code compilation, so you might prefer to stick to p-code when you compile the program in the test phase. (A few types of applications can't be tested within the IDE, most notably multithreaded components.) If your application spends most of its time accessing databases or redrawing windows, compilation to native code doesn't significantly improve its performance because the time spent executing Visual Basic code is only a fraction of the total execution time.
We've come to the end of this tour de force in the Visual Basic IDE. In this chapter, I've illustrated the basics of Visual Basic development, and I hope I've given you a taste of how productive this language can be. Now you're ready to move to the next chapters, where you can learn more about forms and controls and about how to make the best of their properties, methods, and events.
Chapter 3: Forms This chapter 3 through 5 focus on forms, intrinsic controls, and the VBA language, and contain a lot of reusable, optimized routines.
Chapter 3.1: Introduction to Forms Chapter 3.2: Common Properties Chapter 3.3: Common Methods Chapter 3.4: Common Events Chapter 3.5: The Form Object
Introduction to Forms Forms are the first Microsoft Visual Basic objects you get acquainted with. Although you can write useful programs with only rudimentary user interfaces command-line driven utilities, for example most Visual Basic applications include one or more forms, and so you need to be familiar with their properties and features. Despite their different natures, forms and controls have one important thing in common: All of them are Visual Basic objects, and as such they expose properties, react to methods, and raise events. In this sense, Visual Basic is said to be an object-based programming language because the developer's job consists of reading and modifying objects' properties, calling their methods, and responding to their events. Moreover, Visual Basic can be considered a visual programming environment in that the appearance of such objects can be defined by means of interactive tools at design time and without writing any code. Forms and controls expose dozens of properties, and when you explore them in the Object Browser you might legitimately wonder how you can learn the meaning of all of them. It takes some time until you realize that there are a few recurring patterns and that most of the properties are shared among forms and among most types of controls. In the end, properties that are peculiar to form objects or to a given class of controls are relatively few.
This consideration led me to structure this and the following chapter in a somewhat unusual way. Most language manuals introduce forms first, describe each intrinsic control class and illustrate its features, passing from one control to the next, and so on. In my opinion, this approach forces you to study each particular object as if it were a separate case. Such fragmentation of information makes it difficult to get the big picture, and in the end it makes for a steeper leaning curve. Worse, this mnemonic effort doesn't help much in understanding how things actually work behind the scenes. For example, why do some controls expose a TabIndex property but not a TabStop property? Why do some controls support the hWnd property, while others do not? After some thinking, I decided to depart from the typical control-bycontrol description and focus instead on the many properties, methods, and events that forms and most intrinsic controls have in common. The features and peculiarities of forms are covered only later in this chapter, and Chapter 5 is entirely devoted to Visual Basic's intrinsic controls. This means that you won't see complete programming examples until the second half of this chapter, even though I use some shorter pieces of code that explain how a property can be used or how you usually react to the events that are shared by most types of controls. After all, when you're working in the Visual Basic environment, the complete list of all the properties, methods, and events supported by each object is always just one keystroke away: Just press F2 to display the Object Browser or F1 to get more complete and descriptive help. You don't want to read the same information here, do you? I have another reason for explaining common properties in one section. In its six versions, Visual Basic has undergone many important changes: Each version has added new features and, consequently, forms and controls have acquired more and more new properties, methods, and events. Backward compatibility has always been a primary goal in Microsoft's plans, however, and old features are still supported. In fact, you can often load a Visual Basic 3 project in the Visual Basic 6 environment and run it without changing a single line of code. (The most notable exceptions are code that refers to external libraries and controls that access
databases.) Backward compatibility has its drawbacks, though, the first of which is the ever-growing list of properties, methods, and events. For example, there are duplicated sets of properties that have to do with drag-and-drop, and there are two distinct ways to set font attributes. The result is that most beginning programmers are confused, and more seasoned developers tend to continue to use the old (and often inefficient) features because they don't want to learn a new syntax. I hope that the following descriptions of common properties, methods, and events can contribute to making things clearer to both kinds of readers.
Common Properties At first glance, it might seem that Visual Basic 6 supports countless properties for various objects. Fortunately, there's a set of properties many objects of different classes share. In this section, we'll examine these common properties.
Chapter 3.2.1: The Left, Top, Width, and Height Properties Chapter 3.2.2: The ForeColor and BackColor Properties Chapter 3.2.3: The Font Property Chapter 3.2.4: The Caption and Text Properties Chapter 3.2.5: The Parent and Container Properties Chapter 3.2.6: The Enabled and Visible Properties Chapter 3.2.7: The hWnd Property Chapter 3.2.8: The TabStop and TabIndex Properties
Chapter 3.2.9: The MousePointer and MouseIcon Properties Chapter 3.2.10: The Tag Property Chapter 3.2.11: Other Properties
(http://www.f1tutorials.com/Tutorials/VisualBasic6/Chapter3/chapter3.2.html)