An Introduction to Programming Using Visual Basic , Fourth Edition, by David I . Schneider .. books in the BSBIS and BSIT programs. Click on the book cover. Upgrading Microsoft Visual Basic to Microsoft Visual soundofheaven.info Read more NET resources from O'Reilly Related soundofheaven.info Books Resource Center. Visual Basic , I'm very pleased to report, satisfies the needs, requirements, Jeff is the author of several other fine books on topics related to Visual Basic.
|Language:||English, Spanish, Indonesian|
|Genre:||Politics & Laws|
|ePub File Size:||16.64 MB|
|PDF File Size:||13.37 MB|
|Distribution:||Free* [*Regsitration Required]|
PDF Drive is your search engine for PDF files. As of today we have 78,, eBooks for you to download for free. No annoying ads, no download limits, enjoy . Visual Basic ” They are not intended to be a complete reference to Visual Basic. Consult the. Microsoft Visual Basic Programmer's Guide and. Microsoft Visual. Title Introduction: Visual BASIC ; Author(s) Gary Haggard, Wade Steven Holzner, Lou Tylee; Publisher: Bookboon (); ebook PDF, pages, MB .
While these add-ins are real lifesavers. Windows doesn't even know a control is there. 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. Richard Mills Acquisitions and Developmental Chapter 1 is an introduction to the environment for those who have never worked with Visual Basic. No association with any real company, organization, product, person, or event is intended or should be inferred. Press F5 and run it to convince yourself that it indeed works.
To select multiple controls. Note that this shortcut doesn't select controls that are contained in other controls. As an exercise. The values of the properties on which you triple-click are copied from the source controls to all the other selected controls. Notice that once you have selected the Caption property for the first Label control.
I don't know why this property is an exception to the rule stated earlier. This technique doesn't work with all the items in the Properties window. While you can perform this action on a control-by-control basis. Note that you must click the name of the property on the left. Notice that the Caption property of Label and CommandButton controls.
You can view and modify these settings using the General tab of the Options dialog box from the Tools menu. Forms should also follow this convention. The control classes and their recommended prefixes are shown in Table This convention makes a lot of sense because it lets you deduce both the control's type and meaning from its name.
In a sense. The steps along the x. Table Visual Basic assigns it a default name. Microsoft suggests that you always use the same three-letter prefix for all the controls of a given class. For this reason. When you create a control.
The special nature of this property is indirectly confirmed by the fact that it appears as Name in the Properties window. In our example. Because the Name property identifies the control in code. This default naming scheme frees you from having to invent a new. Most likely. In fact. 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.
This is the string of characters that identifies the control in code. This property can't be an empty string. This book sticks to this naming convention. This is as important as selecting meaningful names for your variables.
For example. Naming Controls One property that every control has and that's very important to Visual Basic programmers is the Name property. The Command1 control will be renamed cmdEvaluate. Standard three-letter prefixes for forms and all intrinsic controls. For most controls.
As I mentioned previously. It's immediately apparent that when you have forms with tens or even hundreds of controls. You can also resize a control by dragging one of the blue handles surrounding it when it is selected. Press the 0 key.
TextBox controls—or more to the point. Repeat step 4. In our Rectangle sample application.
Such a sequence is known as the Tab order sequence. 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. Click on the next to last control in the Tab order. Like the move operation. This occurs because Visual Basic prevents you from using the same TabIndex value for two or more controls on the same form.
The control used as a reference in the aligning process is the one that was selected last that is. While these add-ins are real lifesavers. In our Rectangle example. All selected controls will be resized to reflect the size of the control that was selected last. Select the last control in your planned Tab order. In Visual Basic. Even if Label controls never get the focus themselves. This procedure is useful when you know the absolute position or size of the controls.
To have a Label control lend its hot key to another control on the form. When you reach the first control in the sequence. This will give your form a consistent look. But wait. Even more important. This add-in is provided in source code format. 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.
To turn your pretty but useless program into your first working application. By this single action. You'll see that you now have two new files. Press F5 and run it to convince yourself that it indeed works. Visual Basic will ask you for the name of the form file. This tool lets you save a lot of time when arranging the Tab order for forms with many controls. The CDbl or CSng conversion functions are better choices in most cases.
If you don't do that. Choose Save Project from the File menu. Adding Code Up to this point. Text ' Evaluate results and assign to output text boxes.
To write code within the Click event. But you don't have a useful application yet. Visual Basic will default them to the Variant data type.
Or you simply double-click on the control using the left mouse button. To use this add-in. Now that we have completed our project. More precisely.
In this simple program. You can start its execution in several ways: By invoking the Start command from the Run menu. Dim reWidth As Double. Running and Debugging the Program You're finally ready to run this sample program. While this would be OK for this sample program. This is necessary when you need to evaluate the value of an expression that doesn't appear in the code window. The Visual Basic instruction that's going to be executed next— that is.
In some cases. 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.
This program is so simple that you hardly need to test and debug it. Virtually all programs need to be tested and debugged. First Steps with Microsoft Visual Basic 6 Page 15 of designer disappear and be replaced but not necessarily in the same position on the screen by the real form.
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. If you abruptly stop the execution of a program. You can also set and delete breakpoints by left-clicking on the gray vertical strip that runs near the left border of the code editor window.
As a general rule. You'll see the Visual Basic environment enter break mode. When you're finished. To see some Visual Basic debugging tools in action.
Of course. Visual Basic can't save you from this nuisance. 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. After setting the breakpoint at the beginning of the Click event procedure. You can also add the selected expression to the list of values displayed in the Watch window. Some programmers prefer to use Label controls to display result values on a form.
When he or she hangs up. End Sub template. The purpose of the next refinement that I am proposing is to increase the program's robustness. All errors should be trapped and dealt with in a convenient way.
The first type of refinement is very simple. 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.
If this were a real-world. This is the code that you have to add to the procedures: A second refinement is geared toward increasing the application's consistency and usability. The Rectangle Demo program in break mode. Because the txtPerimeter and txtArea controls are used to show the results of the computation.
The end user can copy their contents to the clipboard and paste those contents into another application. To see what I mean. Chapter 1 A suggestion: Let's suppose that your user uses the Rectangle program to determine the perimeter and area of a rectangle. The lines you would add are in boldface. How can you be sure that those values won't be mistaken for good ones? The solution is simple.
You can make them read-only fields by setting their Locked property to True. It takes a few seconds to create the Rectangle. That's why you can often hear Visual Basic developers talking about p-code and native-code compilations to better specify which type of compilation they're referring to.
In this case. I can recycle all of my old hard disks that aren't large enough for any other use. Another benefit of p-code is that you can execute it step-by-step while the program is running in the environment. See Figure But this doesn't mean that you can pass this EXE file to another user and expect that it works. Before I conclude this chapter. I found a very simple and relatively inexpensive solution to this dilemma: I use one computer with removable hard disks.
At some time during the program development. DLL file. Visual Basic has always offered this feature. P-code is a sort of intermediate language. By comparison. This is a capability that many other languages don't have or have acquired only recently. This is a great productivity bonus unknown to many other languages. To see how the On Error statement works. MsgBox "Please enter valid Width and Height values". Visual Basic is a very productive programming language because it allows you to build and test your applications in a controlled environment.
If your business is software development. 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.
If you develop software professionally. There are several reasons to do this: If you're an independent developer. And since a clean system requires only hundreds of megabytes of disk space. The compilation process doesn't necessarily mean that you aren't using p-code. Visual Basic makes the compilation process a breeze: All Visual Basic programs. This is possible because Visual Basic converts your source code into p-code and then interprets it. Visual Basic creates an EXE file that embeds the same p-code that was used inside the development environment.
In the Visual Basic jargon. Text Ensure that they are positive values. Forms and controls expose dozens of properties. A few types of applications can't be tested within the IDE. In this chapter. In this sense. In the end. 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.
Now you're ready to move to the next chapters. In general. Visual Basic is said to be an object-based programming language because the developer's job consists of reading and modifying objects' properties. 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.
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. All of them are Visual Basic objects. Despite their different natures. I've illustrated the basics of Visual Basic development. You can opt to compile to p-code or native code in the Compile tab of the Project Properties dialog. But here are a few reasons why you might decide to create a p-code executable: Although you can write useful programs with only rudimentary user interfaces—command-line driven utilities.
The features and peculiarities of forms are covered only later in this chapter. Remember this exception when writing code that modifies the Height property for all the controls in a form.
The most notable exceptions are code that refers to external libraries and controls that access databases. I decided to depart from the typical control-by-control description and focus instead on the many properties. For more information about the twip measurement unit.
Just press F2 to display the Object Browser or F1 to get more complete and descriptive help. As far as I know. In my opinion. I have another reason for explaining common properties in one section. But you can't change the unit used for forms because they have no container: Most language manuals introduce forms first.
This means that you won't see complete programming examples until the second half of this chapter. After some thinking. Why do some controls support the hWnd property. The result is that most beginning programmers are confused. Backward compatibility has always been a primary goal in Microsoft's plans. ComboBox controls' Height property can be read but not written to. Visual Basic has undergone many important changes: Each version has added new features and. By default. I hope that the following descriptions of common properties.
You don't want to read the same information here. Keep in mind that Visual Basic also offers many interactive commands in the Format menu that let you resize.
First Steps with Microsoft Visual Basic 6 Page 19 of This consideration led me to structure this and the following chapter in a somewhat unusual way. You can also access and modify these properties through code to move or resize objects at run time: These values are always relative to the object's container—that is. After all. A control can also be contained in another control. While you can enter numeric values for these properties right in the Properties window at design time.
In this section. In its six versions. Backward compatibility has its drawbacks. This happens because the height of a ComboBox control depends on the control's Font attributes. Such fragmentation of information makes it difficult to get the big picture.
The Left. Top and Left properties are relative to such a container control. My second suggestion is if you want to use custom colors. In other cases. When you're setting one of these two properties in the Properties window. CommandButton controls are peculiar in that they expose a BackColor property but not a ForeColor property. You can choose from several ways to assign a color in code. If you don't see it.
The colors of a few controls—scroll bars. I also have a third suggestion: Never mix standard and custom colors on the same form. Note that all the values of these constants are negative. Because the default value for the Style property is 0-Standard. Visual Basic constants for system colors. Visual Basic provides a set of symbolic constants that correspond to all the colors that appear in the System tab in the Properties window at design time: Two different ways to set the ForeColor and BackColor properties at design time.
My first suggestion is always use a standard color value unless you have a very good reason to use a custom color. System colors display well on any Windows machine. Font objects expose the Name. Visual Basic supports the QBColor function: Dealing with fonts at run time.
In this book. Print Font. Size property or the equivalent FontSize property is peculiar because in general you can't be sure that Visual Basic is able to create a font of that particular size.
Font It should be made clear. This means that if you later change Text1's font attributes. Name ' Displays "Ms Sans Serif" file: The Font. At design time the Font dialog box lets you modify all font attributes at once and preview the result. This behavior is perfectly consistent with the Font object's nature.
TIP You can use the Set command to assign whole Font objects to controls thus avoiding having to set individual font attributes for each control. Visual Basic 6 still supports old-style Font properties such as FontName. Visual Basic doesn't raise errors when you try to assign invalid font names.
Size ' Prints I mostly follow the newer object-oriented syntax. The short code snippet below proves this. You can take advantage of this approach—for example. You can use the syntax that you like most because the two forms are perfectly interchangeable. Set Text2. The Text property. While you can't move a control from one form to another using the Parent property which is read-only.
No intrinsic control exposes both a Caption and a Text property. Because you're assigning objects and not plain values. For a number of reasons. Picture1 form's surface.
These two properties are correlated. This is a leftover notion from Visual Basic 3 days. While we are on this topic. More frequently. This consideration has been followed in this book: Most of the time. Name Page 23 of ' Displays "Arial" The Caption and Text Properties The Caption property is a string of characters that appears inside a control or in the title bar of a form and that the user can't directly modify.
I specify the default property. I always try to specify the name of all the properties referenced in code because doing so tends to make the code more readable. Invisible controls are automatically disabled. TIP Most controls change their appearance when they're disabled.
The hWnd Property The hWnd property doesn't appear in the Properties window because its value is available only at run time. But note that a missing hWnd property in an external ActiveX control doesn't necessarily mean that the control is windowless because the control's creator might decide not to expose the window's handle to the outside.
Lightweight controls such as Image controls. The default value for this property is True. When the application raises an event such as resizing. All subsequent operations that Visual Basic performs on that control—resizing. From a practical point of view. If it does. The Label. Visual Basic just simulates the existence of that control: It keeps track of all the lightweight controls and redraws them each time the form is refreshed.
This feature can often be exploited to reduce the amount of code you write to enable or disable a group of related controls. To give you an idea of what this means in practice.
All mouse events for disabled or invisible controls are passed to the underlying container or to the form itself. Even though they appear similar at a first glance. Visual Basic controls—both intrinsic controls and external Microsoft ActiveX controls—can be grouped in two categories: But these controls now expose a Locked property that. Visual Basic will disable all contained controls. Some programmers set the Enabled properties to False for TextBox or ComboBox controls that must work in a read-only mode.
This is reminiscent of the way things worked under Visual Basic 3 and previous versions. When you place a standard control on the form. Generally speaking. The hWnd property returns the bit integer value that Windows uses internally to identify a control. This trick works better if you also set the container's BorderStyle property to 0-None. Visual Basic runtime calls an internal Windows API function and passes it the handle so that Windows knows which control is to be affected.
Most intrinsic controls support this property. Visual Basic asks the operating system to create an instance of that control's class. For more information about standard and windowless controls. To grasp the difference between the two groups.
A trip to the Object Browser reveals that the TextBox. If you have a good reason to disable a control but still display it in an active state. Windows doesn't even know a control is there. Even if you're not going to use this property in your code. This means that users can scroll through their content but can't accidentally modify it. To understand whether a control is lightweight. If an object works as a container for other objects—for instance.
You can exploit this feature to use Label and Frame controls to provide hot keys to other controls: The TabIndex property is also supported by Label and Frame controls. Visual Basic checks that control's MousePointer property. If you need to alternate among multiple cursors for the same control but don't want to distribute additional files. Visual Basic uses the value stored in the form's MousePointer property. MousePointer property is set to a value different from 0-vbDefault.
If you want to show an hourglass cursor. MousePointer is 0 and the mouse cursor is over a control.. The actual path may differ. Windows permits a very flexible mouse cursor management in that each form and each control can display a different cursor. But when the mouse floats over a different application or the desktop. For example.. MousePointer is 0 and the mouse is over a form's surface or it's over a control whose MousePointer property is 0.
See the section "Setting the Tab Order" in Chapter 1. Note that this property is read-only at run time for controls that belong to a control array. Note that Visual Basic raises an error if you reference the Index property of a control that doesn't belong to a control array. Most intrinsic controls support the Appearance property. Figure shows you helpful advice from a ToolTip.
Tag isn't the only property provided by Visual Basic to any control: Forms also support this property. Only two intrinsic controls support this property—PictureBox and Data controls—but several external ActiveX controls can be aligned in this way.
How can I be so certain that all controls support this property? The reason is that the property is provided by Visual Basic itself. ToolTips are those tiny. In Visual Basic 5 and 6. Visual Basic 6 comes with a lot of ready-to-go custom cursors. Possible values for this property are 0-None. You can have Visual Basic automatically attach a control to the border of its parent window by setting its Align property to a nonNull value.
Open the Control Panel window. This is true even for ActiveX controls. For all your new applications. The Tag property has no particular meaning to Visual Basic: It's simply a container for any data related to the control that you want to store. Visual Basic creates controls with a three-dimensional aspect. The Index property is the key to building control arrays. You might decide to do so for visual consistency with older programs.
TabStop is present only if the control can actually receive the focus. The BorderStyle property is supported by a few intrinsic controls. These properties are collectively known as extender properties. The Tag property is distinctive because it's guaranteed to be always available. The Tag Property All controls support the Tag property.
You can set this property to 0-None to suppress a border around the controller to 1-Fixed Single to draw it. Note that you have no control over the position or size of ToolTip windows and can modify their foreground and background color only on a systemwide basis.
Note that a few extender properties are available only under certain conditions. The meaning of this property varies from control to control.
Until Visual Basic 4. If you don't want to create a control array. Other Properties The Value property is common to several intrinsic controls. I explain control arrays more fully in Chapter 3. The DragMode and DragIcon properties as well as the Drag method were used to drag controls on the form. You use LinkMode. The following example changes three properties: These days. Dynamic Data Exchange was the preferred way for two Windows programs to communicate. You normally don't need to explicitly call this method because Visual Basic automatically refreshes the control's appearance when it has a chance usually when no user code is running and Visual Basic is in an idle state.
A tiny ToolTip tells you to enter your name. But you can explicitly invoke this method when you modify a control's property and you want the user interface to be immediately updated: The Refresh Method The Refresh method causes the control to be redrawn. TIP The Move method should always be preferred to individual property assignment for at least two reasons: This operation is two to three times faster than four distinct assignments. OLE Drag and Drop properties.
Next file: The Move Method If a control supports Left. Move Left. As I mentioned in the description of individual properties. I won't cover DDE in this book. The old properties are still included for backward compatibility. Move 0. Refresh ' Update the label immediately. Visible And Text1. SetFocus End Sub Here's another possible solution: It also avoids reentrancy problems that can occur.
A potential problem with the SetFocus method is that it fails and raises a run-time error if the control is currently disabled or invisible.
Visual Basic automatically moves the focus on the next control in the Tab order sequence. SetFocus End If And here's the code for the other possible approach. Because you can't use SetFocus on invisible controls. Here's the code for the former approach: If you want to update all the controls on a form but you don't want the end user to interact with the program. On Error Resume Next Text1. The drawback of this second approach is that it affects the Tab order of all other controls on the form.
You just execute this method file: The control whose TabIndex property is set to 0 receives the focus when the form loads. But you should be aware that DoEvents performs additional processing as well—for example.
If Text1. You need to call this method only if you want to modify the default Tab order sequence that you implicitly create at design time by setting the TabIndex property of the controls on the form. Enabled Then Text1. Visual Basic fires a Click event. This means that the ZOrder method can change the relative z-order of a control only within the layer it belongs to.
Visual Basic 6 forms and controls support common events. ZOrder 1 Text1. Relative z-order of controls. This behavior is useful because it lets you deal with the two different cases in a uniform way. In other words. At any rate.
ZOrder ' Move it in front. You can't use this method. First Steps with Microsoft Visual Basic 6 Page 29 of without any argument if you want to position the control in front of other controls. To get this information. This makes it difficult to distinguish single clicks from double-clicks because when Visual Basic calls your Click event procedure you don't know whether it will later call the DblClick procedure.
TIP file: The ZOrder method also applies to forms. Note that you can set the relative z-order of controls at design time using the commands in the Order submenu of the Format menu. Also notice that when you double-click on a control. The actual behavior of the ZOrder method depends on whether the control is standard or lightweight. Click and DblClick events don't pass arguments to the program. But don't be fooled by this apparent simplicity because the Click event can occur under different circumstances as well.
You can send a form behind all other forms in the same Visual Basic application. Whenever the contents of a control change. This behavior often leads to some inefficiencies in the program. It's passed the ANSI code of the key that has been pressed by the user. The KeyPress event is the simplest of the three. At first glance. Both scroll bar controls raise the Change event when the user clicks on either arrows or moves the scroll boxes.
In practice. Visual Basic fires a Change event. GotFocus fires when a control receives the input focus. First Steps with Microsoft Visual Basic 6 Page 30 of While you shouldn't assign separate effects to click and double-click actions on the same control. The KeyPress. As I explained in the previous section. The Change event is also supported by the PictureBox. But be careful.. The Change event also fires when the contents of the control are changed through code.
TextBox and ComboBox controls raise a Change event when the user types something in the editable area of the control. Visual Basic 6 has introduced the new Validate event. For all other keys—including arrow keys. The exact sequence is as follows: KeyDown the users presses the key. The former is the code of the pressed key. You usually test this value using a symbolic constant. You should note that KeyPress. You can also "eat" a key by setting this parameter to 0. End Sub The KeyCode parameter tells which physical key has been pressed.
KeyCode and Shift. X As Single.
Y As Single file: Monitor mouse state using the MouseDown. The coordinates are always relative to the upper left corner of the control or the form. Shift As Integer ' Restore normal operation. This circumstance. You can see the results of running this code in Figure The MouseDown. You don't want to write the same piece of code in the KeyDown event procedure for each and every control on your form. Following Figure is a code sample that displays the status and position of the mouse on a Label control and creates a log in the Immediate window.
Note the negative y value when the cursor is outside the form's client area. Use the form's ActiveControl property if you need to act on the control with the input focus. All of them receive the same set of parameters: This detail is what makes the previous code example work correctly after a button release: The current status is updated by the extra MouseMove event. This behavior reflects how controls work under Windows and shouldn't be considered a bug.
I'll show a number of examples that are centered on forms' singular features. Keep in mind the following points: The most important visible object is undoubtedly the Form object because you can't display any control without a parent Form.
It's interesting to see how MouseDown. All the MouseMove and MouseUp events fired in the meantime might receive negative values for the x and y parameters or values that exceed the object's width or height. Print descr End Sub While writing code for mouse events. Note that the second MouseDown event isn't generated. When you move the mouse cursor outside the form area. You can't move a captionless form using the mouse as you normally do with other types of windows.
Feel free to create new form templates when you need them. TIP To create a captionless resizable window. You can create forms from scratch. Fine-Tuning the Performance of Forms A few form properties noticeably affect performance. And you can make your window unmovable by setting the Moveable property to False. The third new property is ShowInTaskbar. If you want the form to start in maximized state. Visual Basic 5 added three important form properties.
You can set these properties only at design time. The complete path of Visual Basic's template directory can be read and modified in the Environment tab of the Options dialog box. If you assign a non-empty string to the Caption property at run time. Form templates offered by Visual Basic 6. Apart from assigning a suitable string to the form's Caption property. If you don't see the dialog box shown in Figure Next you must decide what should appear on the title bar. Selecting the right values for these properties is important because you can't change them at run time through code.
Assigning it an empty string at run time makes the title bar disappear again. A form template doesn't necessarily have to be a complex form with many controls on it. BorderStyle is one of the properties that largely affects the form's behavior. Visual Basic can quickly restore file: If you're creating a floating.
Captionless forms appear in the taskbar as "blank" forms. First and foremost. To create a nonresizable form. You can have the form appear in the center of the screen by setting its StartupPosition property to the value 2-Center Screen. Its default value is 2-Sizable. Basic Form Properties After creating a form and resizing it to meet your requirements. Even an empty form with a group of properties carefully set can save you some precious time. To produce your custom form templates.
First Steps with Microsoft Visual Basic 6 Page 34 of You create a new form at design time using the Add Form command from the Project menu or by clicking on the corresponding icon on the standard toolbar. Visual Basic creates the form's title bar on the fly. If you have more forms running at the same time. Visual Basic creates a persistent bitmap as large as the largest possible size for the form.
Visual Basic doesn't have to create a clipping region. AutoRedraw's default value is False: If you don't execute graphic methods. Compare this figure with Figure If you execute many graphic methods—such as Line.
Francesco Balena Clearly Visual Basic: Programming with Microsoft Visual Basic Read more. Microsoft Visual Basic: Game Programming for Teens. Microsoft Visual Basic game programming for teens. Upgrading Microsoft Visual Basic 6. Programming Visual Basic Visual Basic.
NET Programming. Programming Microsoft Visual Basic. Net Core Reference. Programming Visual Basic. NET programming. Visual Basic Microsoft Office Reference.
Beginning Microsoft Visual Basic Mastering Microsoft Visual Basic