Visual Basic Tutor
Visual Basic Tutor
• 1991 VB 1 (May)
• 1992 VB 2 (Fall)
• 1993 VB 3 (Summer)
• 1995 VB 4 (August)
• 1997 VB 5 (February)
• 1998 VB 6 (Summer)
• 2001 VB.Net?
I personally failed to see the value of VB when it was first released and continued
working with DOS QBASIC up until VB3 was available. By that time, VB was mature
enough that most pundits declared that it had "arrived". Even though I switched over, I
continue to use DOS BASIC for very short file manipulation routines where a user
interface is generally unnecessary.
The history of VB is actually pretty exciting. You might think that VB was a natural
follow-on to the DOS versions, but remember that BASIC was considered a non-
professional programming language and that Microsoft had no real reason to push BASIC
to the next level - Visual Basic.
So what happened? I wasn't there, so I'm limited to 3rd hand versions of the story. Most
versions seems to agree that a visual programming environment known as Hypercard was
created by Bill Atkinson and that it was demonstrated to Bill Gates who then supported
it's development as a Microsoft extension to BASIC
What's not clear from my readings is how much of VB was a Microsoft invention or how
much of VB's genesis is owed to the MacIntosh industry. There's an interesting online
version of VB history that you might be interested in reading - one that might explain
why there is no Mac version of Visual Basic.
VB Versions
Visual Basic comes in 3 commercial editions. For beginners who do not expect to move
to the next level as a paid professional programmer I suggest the Learning Edition. For
anyone who does plan to program as a career I strongly recommend the Professional
Edition. If you're a corporate programmer then the Enterprise Edition is the way to go -
but let the company pay for it !
• Learning Edition
This is totally suitable for learning to program in Visual Basic. It includes all
intrinsic controls, plus grid, tab, and data-bound controls. Documentation
provided with this edition includes the Learn VB Now CD plus the Microsoft
Developer Network (MSDN) Library CDs containing full online documentation.
• Professional Edition
Has the complete set of tools that almost any VB programmer requires. It includes
all the features of the Learning edition, plus additional ActiveX controls, the
Internet Information Server Application Designer, integrated Visual Database
Tools and Data Environment, Active Data Objects, and the Dynamic HTML Page
Designer. Documentation provided with the Professional edition includes the
Visual Studio Professional Features book plus Microsoft Developer Network CDs
containing full online documentation.
• Enterprise Edition
Geared towards the large project that is normally handled by a team of
programmers, this edition is usually seen in a corporate setting. It includes all the
features of the Professional edition, plus Back Office tools such as SQL Server,
Microsoft Transaction Server, Internet Information Server, Visual SourceSafe,
SNA Server, and more. Printed documentation provided with the Enterprise
edition includes the Visual Studio Enterprise Features book plus Microsoft
Developer Network CDs containing full online documentation.
VB Advantages
So what makes VB a great programming language? The answer is simply that VB
provides more of the actual code for a programmer than any other non-visual
programming language.
If you've ever programmed in the older BASIC or other command line programming
language, then you'll remember that the programmer had to write the code for the entire
user interface. Todays windows, buttons, lists, and other application features such as
menus were not built-in to the BASIC programming language. Programmers had to
create the code for these features on their own!
As much as 80% of a programmer's time was spent writing code to create the user
interface to his applications (the visual interface). To eliminate this huge drain on a
programmer's time, Microsoft has provided Visual Basic with the built-in capability to
create the user interface using nothing more than a mouse!
This built-in interface creation capability has had the further benefit of standardizing on
the user interface to Windows applications. Today, users can move from one Windows
program to another and see the same basic interface tools to work with - allowing them to
concentrate solely on the unique capabilities of the application.
The bottom line is that you can create an entire application shell (the user interface) very
quickly and then spend most of your time working on the features which differentiate you
application from its competition.
• Delphi
Based on Pascal programming language, Delphi has developed a huge following.
Designed to be compatible with the OCX family of controls that support VB,
Delphi is very similar to VB. The single best feature of Delphi is that it creates
completely stand-alone EXE files - unlike VB which requires the distribution of a
huge number of supporting files for even the smallest of applications. Delphi's use
of Pascal, instead of a BASIC-derived language is probably one of the primary
reasons that VB programmers don't jump ship.
One of the reasons I stay with VB is the huge following that VB enjoys. for
programmers, this translates into the widest range of books, USENET
newsgroups, commercial controls and other tools than any other programming
language. Delphi suffers strongly from this. While Delphi users are known to be
fanatical about their choice, the overwhelming popular vote goes to VB.
Bottom line is that if I had the money I'd defintely become bi-lingual and use
Delphi as my second language. The small distributable EXE's are very important,
especially for Internet distribution of applications. However, with limited funding
I choose to stay with the industry leader.
• Visual C
If you've take a C class, you'll understand easily the reason that Visual C has not
become the most popular programming language. The visual part of Visual C is
virtually identical with VB in terms of the ease of creating Windows/NT
programs. It's the underlying difficulty of the C coding process that keeps users
away.
Bottom line is that if I were planning a corporate career I'd easily take on Visual
C++ as my second language. The huge corporate base of C programs and the
continued reliance by corporations on the more powerful C language means that
job opportunities will continue to be strong for programmers with C experience.
In particular, there are no HELP files and you cannot create .EXE files for distribution to
users and friends. The program you write can be saved but can only be run on systems
which have VB6 installed.
Even with those limitations, it is still a good way to evaluate Visual Basic. Since you get
a book with the software, it definitely is a bargain since each of the books costs about
$30. You can go to my VB Books page for more details about these books.
Step-by-Step Instructions
Okay, let's make VB proficiency a step-by-step process. The bottom line is that
you have to read, then practice what you read. Here's the guidelines for what to
read, and in which order.
It is an excellent manual and can be bought from Microsoft Press. Read it front
to back, and don't skip pages. Type in all the examples and run them until you
understand them. Save what you type in. Keep a notebook of where you found the
code examples. You will likely use most of them over and over on future projects.
Read it a second and third time if you want to get maximum value from it. I've
read mine so often that there are more highlighted sections than there are
unmarked ones. If you can't talk yourself into reading the whole thing, then
consider these suggestions:
Your tools are the VB language statements and the VB controls. Imagine hiring a
carpenter and when you hand him a hammer he says "What's this for?". You owe
it to yourself and your employer to know what VB tools are available and how to
use them. Reading the manual is the start, but it is only a start. I've prepared two
summaries which show you the kind of studying that really help your training.
The first is a language summary and the second is a control summary. In the
language summary I've summarize the VB statements according to the type of
task they can perform. For controls, I've identified every single property, method
and event. The key thing about the summary is that you'll find out exactly what
similarities there are between tools, plus you'll see exactly how one tool differs
from the other.
Go through each of the samples that came with VB (in the samples directory). Pay
special attention to the procedures that are provided in the samples. You will be
able to re-use these in your own project over and over. I also have provided
several sample programs that you might find useful. I provide annotated source
code for these sample applications to help your understand what the code does
and why I wrote it the way I did.
• Step 4. VB FAQs
Read the VB FAQs. Their information focusses on questions which are asked
over and over by VB users, particularly newbies. Unfortunately there is no one
single FAQ these days, nor are all of them kept current. I have some older ones
located here.
Once upon a time, Microsoft offered files with list of Questions and Answers
about VB. It was called the VB Knowledge Base. Now, Microsoft has integrated
the VB KB into its site-level Knowledge Base and you can access it online at
http://support.microsoft.com/support
The older files are still available at the Microsoft FTP site and are worth reading
all the way through (at least the titles). The reason these articles are there is that
VB users wanted to know how to do things. You may not know what half of the
articles are good for right now. But when you run into the same limitations as are
addressed by the articles, you'll be glad you know what is in the Knowledge Base.
If you want to pare down the effort, take a look at my list of Top VB KB
Articles.
Go through the VB Help file, just like it was a manual. Pay close attention to the
examples. If you can, find a program which will print out the HELP file (or at
least portions of it, since the VB help file is really huge!) to take with you when
you won't be at a PC.
• Step 7. Books
Generally, I recommend learning VB from books. This allows you to learn at your
own pace and to go over difficult materials as often as needed. I recommend
classwork only after you've learned all you can, or after you've reached a plateau
and need an instructor to help go to the next level. There are two books I normally
recommend. The Microsoft Visual Basic 6.0 Programmer's Guide is the first book
anyone should touch. It's essentially the manual for VB, but you do have to pay
extra to get it. It covers basic and advanced topics, enough to guide you to an
intermediate level of capability.
If you look these over but they're not what you want, be sure to take a look at my
VB book reviews. I've provided a listing of over 350 VB books, including
reviews and Tables of Content, to help you in making a purchase decision.
Download and evaluate as many as possible of the 3rd party shareware tools
located at the various archives. A simple approach is to head over to the VBXtras
online catalog and for a look at a good selection of the best VB apps available.
General Guidelines
• Rule 1. Visual Basic is BASIC at its core.
Okay, so there are a lot of major differences between the two, but when it comes
to coding, if you know BASIC, QuickBasic or QBASIC then you have an
excellent foundation for succeeding with Visual Basic. The event-driven model
used by VB is new, as are many of the VB concepts, but you will be using
BASIC-like code to implement the VB concepts. The point is not to let VB take
on an aura of something strange and mysterious. It's not called Visual BASIC for
nothing.
Cross-training is a myth. You can't get good at running by jumping, and you can't
get good at coding by reading. All the materials listed in the Step-by-Step section
are worthless unless you practice what you have read. This means code, code, and
more code!
I hate it when my kids say "Dad, I can't quote the exact answer but I know where
to look it up!". My personal philosophy is that as a programmer I want to create
my applications as quickly as possible. When I have the syntax of VB commands
memorized I can whip through an application in record time. If I had to stop and
look up the syntax in the user's guide for every line of code I wrote, I'd more than
triple the time it takes to complete an application. The moral of this story is that
when you are reading the manuals, read with the intent to remember exactly what
you read, not just where it can be found!
The corollary to this rule is that you must learn to type efficiently. I'm always
amazed at my coworkers amazement at how fast I type. For me, to think it is to
have it typed already. The value of this should be obvious. If you can't type
efficiently you'll not only slow down how fast you record your ideas, but you'll
also interrupt your creative process with the mundane task of watching your
fingers single-stroke an idea. Have you ever noticed how distracting it is to listen
to a slow speaker? Same idea applies to typing!
In the early stage of your learning cycle, don't get off on a tangent by looking into
low-percentage learning tools (i.e., User Groups, USENET, and other group
activities). These tools are excellent for getting an answer to a specific question,
but do not provide as much return on investment of your time as individual study
and coding practice. You shouldn't hesitate to seek help when a particular
problem is slowing you down, but group activities rarely provide value to you
except for a fraction of the time you're involved with the activity.
Please note that as your skills develop, and after you have absorbed much of the
literature available to you, that group activites will take on more importance. At
that point, you will better understand where your deficiencies lie, and can take
better advantage of group activities.
Remember to start with small coding projects and work your way up to more
complex ones. The examples in the VB Programmer's Guide (that came with VB)
are very short and you should have little trouble with them. Programming skills
are additive and you will get more frequent, positive feedback if you tackle many
little projects instead of a few large ones. You might try out my own sample VB
project
As soon as you're comfortable with the basic skills, then start a big one of your
own choosing. Until you have a personal need for a capability of VB, reading
about it is like hearing about sex! You've got to do it to appreciate how great it is!
Big projects have a way of causing you to reach the limits of Visual Basic in a
way that little projects don't. It is often the interaction of VB elements which
gives a programmer difficulty, and large projects provide more of this than small
projects. Notice that the intent is not just to have a program with many lines of
code, but to have a project that uses as many features of VB as possible. Again,
you might try out my own sample VB project which incorporates a wide variety
of VB features.
This follows from Rule 2. Often, a 3rd party vendor puts hundreds, or thousands
of hours into his product. If he sells it to you for under $100, it is an absolute
bargain. As a paid programmer, your job is to get the software completed as
quickly as possible and at the lowest cost. When you charge $40-$75 an hour, you
are treating your customer poorly if you spend hours recreating something that is
already available as a 3rd party tool for less money than you would charge for
your own efforts.
I don't recommend the use of 3rd party tools until after you have mastered the
basics of VB and have had the experience of trying to create your own code to
replicate a 3rd party tool. You'll appreciate it more that way. I maintain a list of
software vendors at my site.
I have a strong opinion about classes. You don't get the most from a class unless
you have worked with the topic on your own before coming to class. So, if you
decide to take a class, then I recommend that you wait until you have used VB
enough that you have a mental list of things you don't seem to understand. Then
take a class and you'll get more out of it. If you go in with no prior knowledge,
you won't appreciate what is significant or what is not.
Certification Tips
How can you show a prospective employer that you have the basic skills to
perform the job he has open? How do you know yourself whether you meet some
minimum skill set that will help get you a good paying job?
Getting the certification does not necessarily mean that employers will come
runing to your door, nor does it mean that your current employer will give you a
raise in pay (only 20% of programmers say this happens). Like any other
professional position, the experience you bring to the job and the applicability of
that experience to your employer's needs are the primary factors which affect your
ability to get a job or to get ahead in the one you have. But, all other factors being
the same the MCSD certification can make the difference in select of you over
competition for assignments. Just the fact that you showed the initiative to get the
certification provides an indication to your boss/prospective employer that you
have skills which go beyond just the mechanical ability to generate code.
So, if you're considering getting MCSD certification, then you might find the
following certification tips useful. Also, here's another set of MCSD tips by James
Foxall, author of MCSD in a Nutshell.
Most of us have only limited time to devote to issues in our lives. Preparing for
the MCSD tests is no different. Just like you would spend time to design your
program before writing code, you will need to spend time making a list (and
schedule) of the topics you will need to study, estimating the time you will take
(or have available) to prepare, and using that schedule to determine if you are
making sufficient progress to take the test on the planned date. Use this structured
approach to preparing and you will not only get the daily feedback on your
preparations but also you will gradually build the confidence that you are ready
for the test when the time comes.
This may sound self-evident, but remember that the purpose here is not to show
that you know everything about VB, but rather to show Microsoft that you
understand the things they consider important. Take a look at prior tests to
understand what is likely to be on the test and focus on that. It's okay to disagree
on what's important in VB - but plan to study that later when you're not preparing
for the MCSD test. The Microsoft Certification Site is a key place to visit for
details and information on preparing for the test.
The problem with my second tip is that the best way to know what is on the test is
to take the test itself. By taking the test ASAP, even though you might fail, you
achieve several results. First, you find out what topics are covered on the test.
Second, you have a chance to get over the nervousness that often accompanies the
taking of a test such as this. Once you've been exposed to the test, the next time
you take it you will be more relaxed and most likely perform better. According to
Lisa Mann at O'reilly, over 50% of the programmers that take the test fail it the
first time they take it. So, if you fail, don't sweat it. No one knows it but you, no
one really cares, most folks fail just like you did, and now you're better able to
prepare for the next one.
Like almost any information, it seems easier the more you use it. When you're
doing your studying then you should make an effort to use the techniques you're
using. Test questions are not usually tricky, but are geared to show that you
understand the material. If you have practiced using the information that you've
learned - over and over - then the questions actually become trivial. I also find
that test questions can only go so deep - so the more that I have used the
technique, and understand the details of the technique, the less likely I can be
tripped up by relatively superficial test questions. As a basketball player in high
school (okay, I was on the B squad!) I remember that my coach told me "If you
can't do it in practice, then you can't do it in the game!". This lesson directly
applies to your strategy for preparing to pass the test.
When you're learning information, don't stop at just being able to replicate what
you've read, or at just being able to apply it to your application. Some of the best
study time you'll have is when you take the time to examine the code/technique
you're using and attempt to take it apart. Ask yourself questions about what you
know - do you know a lot about it, or just a few facts? Was the material you
studied complete, or was it missing information on some facet of the technique?
How does the next information tie in with what you already know? Does it
replace or compete with what you already know? When should you use it and
when is it the wrong approach to solving a problem? When you think you could
teach it to someone else, then you've gotten a big step closer to full understanding.
Ask any teacher and they will tell you that you don't really know what you know
until you have to teach it to someone else. Reading gives you one level of
knowledge and applying gives another. But neither requires you to sort it out in
your head like explaining to a student what the technique is, why it is important,
when to use it over other options, what the negatives are, and what it's strengths
are. If you don't have someone to teach, then a) simply go to the USENET groups
and try to answer questions or b) get a web site and advertise on it that you will
answer questions for free - then stand by for the avalanche of questions.
I am an avid Country Western dancer (after all, I am from Texas!). I've taken
literally hundreds of lessons, from over a dozen instructors. What I found was that
one instructor was able to teach me some steps, but didn't have the skills to teach
others. Each instructor had his own viewpoint and by getting instruction from
them all I was able to develop a clear understanding of what I was learning -
seeing it from many different angles. The lesson applies directly to VB. Read
from several books, read from the USENET, read the available newsletters, read
VB HELP, and listen to as many instructors as you can. It will pay off in a
significantly better understanding of the materials you need to know.
Project Definition
A typical VB application might consist of more than one forms, each of which may have
multiple controls. In VB, the information about each form (it's own properties as well as
those of the controls that are on the form) is saved into it's own file. In fact, there are
several types of files which VB creates (we'll cover them all later in the tutorial).
VB also saves a "project" file which contains the list of files which VB loads when the
"project" is loaded. The project file includes other information, such as the filenames of
controls which are not intrinsic to VB (they exist as separate files with .OCX extensions).
The project file is a simple ASCII text file and may be edited with any text editor,
including NOTEPAD (which comes with Windows). Once you learn the format of the
project file you may have reason to edit it directly but in general, most programmers do
their editing within the VB IDE.
The project file is saved with an extension of .VBP (Visual Basic Project). Other files
saved by VB include the following extensions:
- .FRX : graphics associated with the form
- .BAS : code not associated with control events
The good thing about splitting a project into many files is that you can use a file (form or
otherwise) in one or more projects. If you make a change to the one file, all using projects
see the change.
In the following VB IDE example, you see a project with two forms, each with multiple
controls. The filename of each form is displayed in the project window, as is the name of
a single .BAS file. Together, all three files make up the VB project.
Here is the content for each of the files. You will note that the files are in ASCII text. By
inspection, you can guess what a lot of the line items are for.
• Project File
Type=Exe
Form=2ndForm.frm
Reference=*\G{00020430-0000-0000-C000-
000000000046}#2.0#0#..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE
Automation
Form=testform.frm
Startup="Form1"
Command32=""
Name="Project1"
HelpContextID="0"
CompatibleMode="0"
MajorVer=1
MinorVer=0
RevisionVer=0
AutoIncrementVer=0
ServerSupportFiles=0
VersionCompanyName="Personal"
CompilationType=0
OptimizationType=0
FavorPentiumPro(tm)=0
CodeViewDebugInfo=0
NoAliasing=0
BoundsCheck=0
OverflowCheck=0
FlPointCheck=0
FDIVCheck=0
UnroundedFP=0
StartMode=0
Unattended=0
Retained=0
ThreadPerObject=0
MaxNumberOfThreads=1
• Form 1
VERSION 5.00
Begin VB.Form Form1
Caption = "2ndForm"
ClientHeight = 2280
ClientLeft = 5805
ClientTop = 2055
ClientWidth = 3735
LinkTopic = "Form1"
ScaleHeight = 2280
ScaleWidth = 3735
Begin VB.CheckBox Check2
Caption = "Check2"
Height = 495
Left = 2160
TabIndex = 3
Top = 360
Width = 1215
End
Begin VB.CheckBox Check1
Caption = "Check1"
Height = 495
Left = 240
TabIndex = 2
Top = 360
Width = 1215
End
Begin VB.CommandButton Command2
Caption = "Command2"
Height = 495
Left = 2160
TabIndex = 1
Top = 1320
Width = 1095
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 495
Left = 360
TabIndex = 0
Top = 1320
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
• Form 2
VERSION 5.00
Begin VB.Form Form2
Caption = "Form2"
ClientHeight = 1905
ClientLeft = 6600
ClientTop = 2025
ClientWidth = 3465
LinkTopic = "Form2"
ScaleHeight = 1905
ScaleWidth = 3465
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 375
Left = 2040
TabIndex = 2
Top = 1320
Width = 1095
End
Begin VB.TextBox Text2
Height = 285
Left = 1080
TabIndex = 1
Text = "Text2"
Top = 720
Width = 1695
End
Begin VB.TextBox Text1
Height = 285
Left = 1080
TabIndex = 0
Text = "Text1"
Top = 240
Width = 1695
End
End
Attribute VB_Name = "Form2"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
As you go through more of the tutorial, the content of the files will make more sense, but
even now you can see that the information is not that difficult to decipher.
What is a Form?
Here's a simple Visual Basic form. It looks just like any other form that you use in
Windows applications. The header area has a caption, the control menu, and the
minimize/maximize/close buttons. The large area of the form is called the client area.
Don't be shocked, but all Windows/NT programs consist of one or more windows. In its
simplest form, a window simply consists of a rectangular area of the screen. Anything
that appears inside that area is considered to be part of the window. However, you can
have one window contained inside another. Control objects, which are also implemented
as windows, will be framed by the form window to which it belongs. As an operating
system, Windows 9.X/NT controls the display of the various, possibly overlapping,
windows on the screen.
In Visual Basic, the basic building block of an application is a form, which is simply a
window. The VB IDE can insert forms into your project, and then you can resize the
forms as well as change other properties of the form.
However, controls (checkboxes, textboxes, ...) are also windows. A form is distinguished
from a control in that only forms can exist as standalone objects. When controls are used,
they must be placed in a form. Ok, there are a few exceptions such as the printer object or
the screen object which are not considered part of any form, but are part of a VB
program. I'll talk to these special "system" objects later in the tutorial.
Not to confuse the issue, but controls can also be placed inside of other controls. When
this happens the parent control is known as a container. Likewise, forms are containers
but are the highest level of container there is in a windows application. Forms are always
parents of controls, never the other way around.
There is one exception which I will not cover in these tutorials, and that is a special form
called an MDI form. In this special case, an MDI form is always contained within a
parent form. This is exactly the same type of parent/child relationship which you see in
Word. Each new Word document is contained in its own window, but is always framed
within the larger window that is the Word application.
The MDI (multiple document interface) forms can be very useful in applications where
multiple files/images/documents need to be open at the same time. Other than this brief
mention, I will not cover MDI forms in these tutorials.
Likewise, a form may recognize certain events. All forms recognize the same events, but
there are controls which recognize a broader range of events than forms. Events range
from a simple keypress by the user to the click of a mouse button.
Then, finally, forms and controls also support various actions that may be taken. The
actions are known as methods, and may include such tasks as moving the form, loading it
into memory, or refreshing the form to redraw graphics which may have been
overshadowed when one form was placed on top of another.
Remember that even though this part of the tutorial is focussing on forms, that
Properties/Events/Methods apply to all objects in Visual Basic.
Given that there are over 20 controls available to you in the VB Pro edition, you might be
concerned that learning all of the possible properties, events, and methods could be an
overwhelming task. However, it's not at all that bad. Here's a very helpful piece of
information that makes your task easier: all forms, controls, or objects share many of
their properties, events, and methods!. Re-read what I just wrote! It's a very important
piece of information and it means you can reuse what you learn about one control to help
you learn about other controls. I've created a control summary chart (available in Excel
97 and Excel 5.0 formats. The chart gives the complete list of VB controls (provided in
VB Pro) and lists their properties, events, and methods. The chart is listed in such a way
that you can see the common items, as well as those which are unique to that control.
You'll see that many controls have no unique items at all! In my chart I show 41 common
properties, 20 common events, and 7 common methods. Please note that not every control
uses all the common items! Some common items may be shared by only 2 or 3 controls.
I highly recommend that you look over the chart and become familiar with all of the
items on it. I regularly get questions at my site where the programmer could have
performed a desired task by simply setting a property of the control, if he had just
known about it! Just having the chart gives you the ability to look and see if a control
supports a feature that you need.
Detailed descriptions and sample code for using the items can be found in the VB HELP
file. There is also a Microsoft book call "The VB6 Language Reference" which gives
additional detail for each of the items.
As a prelude to the larger chart, here's a simple listing of the entire set of properties,
events, and methods that are recognized by a form. Don't shy away from looking at this
list in detail because you will use every one of these over and over again! Forms are
particularly critical to the VB programmer because they are the fundamental building
block for every applications.
You'll note that forms, like most objects tend to have many properties, and that the
number of events is much larger than the number of methods. A control can have well
over 100 properties but normal count is usually around 50-70. You'll find that the name
of most of the properties to be very self-explanatory (i.e., caption, name, fontsize,
enabled, ...).
On the other hand, controls are not likely to have more than 25 or so events, and rarely
has more than 10 methods. There are exceptions, but the generalization gives you a feel
for what is involved with most controls.
The control summary chart lets you quickly get to details of which controls supports
which item.
Introduction
When I was writing the sections on the Intrinsic and ActiveX controls, I realized that the
documentation for the controls was somewhat confusing. The MS Programmers Guide,
the MS Component Tools Guide, and the VB HELP files weren't consistent in their
description of what controls were available, nor were they clear as to which controls
come with the Learning and Professional editions of VB.
Intrinsic Controls
In the next section of the tutorial, I cover the 20 controls which are built in to VB. These
controls are called intrinsic controls. Every one of the intrinsic controls are available to
every VB program you write. When you create a "New" VB project, all 20 of the intrinsic
controls will show up in the Toolbox. This is true for all versions of VB.
ActiveX Controls
Microsoft uses this terminology to refer to any control which exists as a separate file
whose extension is OCX. To use an ActiveX control in your VB program, the control
must be registered in the Windows Registry. Usually, the OCX control installation
software handles the registration for you (such as VB does to register the controls it
provides).
If you have a control which has not been registered by other software, you can register it
yourself using the free program provided by Microsoft. The program, REGSVR32,
comes with all version of Windows and is usually found in the Windows folder. To use it,
simply type in:
REGSVR32 control.ocx
where the "control.ocx" is the filename of the control that you want to register.
There are many free controls which can be used freely at design-time. However,
commercial controls require that you install them using a password before you can use
them within your project at design time. If you simply copy an OCX to your system and
register it with REGSVR32, don't be surprised if you get an error message when you try
to put the OCX on a form!
Once you select the intrinsic controls you need, you'll add to your project a few of the
ActiveX controls which provide a specific feature you want in your application. You are
very unlikely to have an application which uses all of the available ActiveX controls.
You'll often find that adding 6-10 ActiveX controls will be the most that any application
requires. If you're like me, you will have 3-4 very versatile controls which you use a lot,
and a very few others which you use on a regular basis.
From the available ActiveX controls, I use the Toolbar, ImageList, and Common Dialog
controls extensively. The Treeview, and Tab Control round off my list of personal
favorites from the ActiveX control list. I probably should make more use of the Progress
bar but most of my applications don't include tasks which make the user wait long
enough to warrant the insertion of a Progress Bar. Likewise, using the StatusBar would
certainly help my programs be more user-friendly, but I just don't seem to generate the
enthusiasm to include it on my applications.
I also depend on third party OCXs. I find that I use the Formula One spreadsheet and the
Crystal Reports reporting controls very often. Other than that I have a few specialty
OCXs which I use, particularly in the graphics areas.
Tutorial: Visual Basic Intrinsic Controls
VB comes with 20 built-in controls. In this section of the tutorial I provide a few
comments about each one, trying to give some useful pointers on the use of each control.
I strongly suggest that you review my control summary chart - available in Excel 97
and Excel 5.0 formats. The chart gives the complete list of VB controls - along with their
properties, methods, and events. The spreadsheet will help you get a "big-picture"
overview of the VB controls. I also strongly suggest you read the HELP file content for
each of the properties/events/methods for these controls. If you don't know the item
exists, then you won't know when to apply it in your applications!
Introduction
All controls are not equally useful. Some you will use on every application you write.
Others you will use only when you have a special need for the features the controls offer.
When you start VB, you'll always find the intrinsic controls displayed in the toolbox. The
controls are built-in to the VB files and do not exist in an external file (with a .OCX
extension) the way the ActiveX controls do. In the toolbox, each of the controls has its
own distinctive icon.
These nine intrinsic controls are pretty much used on every VB application I've written.
Start your learning with these and then branch out. Further down on this page I have a
brief comment on each of the controls.
Command Button ImageBox
CheckBox PictureBox
TextBox ListBox
Label ComboListBox
Option Button
The other eleven intrinsic controls are also valuable but I find myself using these less
often than the others. Also, you'll find that you use fewer of these within an application
than you do of the nine that I listed as the most useful controls.
Database Features
I've put the discussion of databases elsewhere in the tutorial, but you should know right
now that several of the intrinsic controls can display or edit data directly out of a
database. With VB, the ADO Data Control is used to access the database information and
to distribute it on to the other intrinsic controls which can handle database information.
VB uses the terminology "databound" to describe controls which have built-in features
for handling database access.
• Command Button
This one works just like you expect. Press the button and it executes a block of
code.
• CheckBox
Typically this is used for turning on/off some particular feature of your program.
• TextBox
This is the standard way of letting a user edit information. To make it convenient
for the users, learn about the .SELLENGTH and .SELSTART properties which
highlight text in the the textbox.
• ImageBox
Use this to display a picture. Use it over the PictureBox because it takes less
operating system resources.
• PictureBox
While it can display pictures, it also acts as an area on which you can print text
and graphics. Use it for home-grown graphics or print previews.
• Label
As the name suggests, this is used to label other controls. It's pretty passive and
you'll seldom use its items other than the .CAPTION property.
• Option Button
If you use it, you'll use it in groups. VB handles the feature that only 1 option
button can be selected at a time.
• ListBox
This is the first of the intrinsic controls to introduce methods common to some of
the more complex controls. The use of a ListIndex which starts at 0 (not 1) is a
confusing factor that you must watch in your code.
• ComboListBox
Whereas a listbox takes up space on the form, the combolist control minimizes the
use of valuable form real estate. It has 3 modes of operation some of which allow
you to keep your users from entering bad data.
• ADO Data Control
If you're not accessing a database, then you don't need this one. If you are
accessing a database you have to have this control to act as the interface to any
other databound control. The exception is that VB offers ways to access databases
directly from code, but for modest display/edit applications the ADO Data
Control is very effective.
• DirListBox / DriveListBox / FileListBox
You'll almost always use these in combination with each other. Read the HELP
file for how to synchronize them to work together. Often, however, you will use
the CommonDialog Control instead of these.
• Line
It can be used as a static display, or you can animate it with the .VISIBLE
property and the .MOVE method.
• Shape
When the line is not enough, this one supports rectangles and ellipses/circles. As
with the line control, use its items to create animation.
• OLEContainer
If you want to put objects on your VB application which come from other
applications already on your machine (such as Word, Excel, ...) then this control
is very useful. For my needs, I don't like making the assumption that my users
have the application (in a specific version) on their machine to make distribution
of my application go smoothly. I avoid this one whenever possible!
• Frame
It's just a container - it can hold other controls. There are two very good reasons to
use it. If you want multiple groups of option buttons then place each group in a
frame and each group will operate independently. If you want to manipulate
controls as a group (i.e., positioning) then put them in a frame and you can handle
them all at one time.
• Horizontal/Vertical ScrollBar Controls
Basically you let use the slider value of a scroll bar as the input for other code that
you write. These are normally used in conjunction with other controls.
• Timer
This is the most unusual of the intrinsic controls. By setting the .INTERVAL
property this control will automatically create an event on a regular basis. No
other control does this! You can use it to create an action at a certain time and
then turn the control off to prevent repeats.
Introduction
As with the Intrinsic controls, not all of the ActiveX controls are equally useful. Some
you will use on many applications but you will use others only when you have a special
need for the features the controls offer.
When you start VB, none of the ActiveX controls are displayed in the Toolbox. Only the
intrinsic controls are displayed, so you must manually insert the ActiveX controls into the
Toolbox as you need them. To do so, right-mouse click on the toolbox and go to
"Components", select the controls to put on the toolbox and press "OK".
A little tip - in the startup box for VB you can select to open a project which contains
every ActiveX control that VB installed. You might have missed it because that option is
at the end of the list of project types that VB can open for you when you use the
"File/New" menu. Here's a picture of the Toolbox with all of the Pro controls loaded.
All of the ActiveX controls are contained within OCX files. None are built-in to VB. In
some cases, Microsoft put more than one control into an OCX file. We'll give the file
names later.
Of course, everyone will have their opinion but since it's my tutorial I get to give my own
opinion for the most popular Pro controls. These nine intrinsic controls are pretty much
used on every VB application I've written. Start your learning with these and then branch
out. Further down on this page I have a brief comment on each of the controls.
Some of the VB controls are very excellent tools, but they simply aren't needed in many
applications. This list of controls are ones that would be on my list of the best controls
except that they are just not needed that often:
Animation MonthView
DateTimePicker PictureClip
FlatScrollBar Slider
ImageCombo UpDown
MaskedEdit
One of the things you'll notice is that I use a few controls a lot, and don't make a heavy
effort to use every available control. I've thought about it a lot and wonder if VB
programmers out there are like me, or if everyone uses their favorites over and over?
You'll have to decide for yourself which approach makes sense. In the comments that
follow I provide some of the logic which pulls me to one of these controls, or what it is
that keeps me away!
• Animation Control
Personally, I don't do games and I find animation in business programs to be of
marginal value (unless the animation is of real-time generated data). So, this is
one of the controls I seldom use. Interestingly enough, I get a lot of questions
from newbies on how to do animation and I steer them to this control.
• Communications Control
There really are some excellent reasons to become familiar with the MCI control.
Programs like Laplink are hugely successful, primarily over their ability to work
through the serial and parallel ports of a PC. I believe that 98% of all
programmers never have that need. For the remaining two percent, however, this
control can be a god-send.
• CoolBar Control
The concept is great - give your program a look and feel like that of other
programs that your users are familiar with. In practice, most of our users have
been exposed to so many windows programs that an Explorer-like interface or a
Win3.1 application interface are all so easily understood that unless your user is
picking between your program and a second one, I don't believe the look-and-feel
will buy you any more users. Take advantage of it if you want, or just use what
you're familiar with.
• DataRepeater Control
I tend to do things manually. Any control which automatically performs tasks for
me tends to be ignored so long as I can get the job done with tools I'm already
familiar with. This is a habit I really need to break. As I've said before, a
programmer's job is to get the job done quickly and economically. Under those
guidelines, controls such as the data repeater should be high on my list. I'll work
on it!
• DateTimePicker Control
So far, I've never written a program which needed a calendar. I've done many
where a date was entered but usually the date was the current date and that was
easy to provide to the user. I can see where some programmers could put this to
good use.
• FlatScrollBar
The only thing that would entice me to use this is that it can be made to take on
both horizontal and vertical orientations. That makes it pretty versatile.
Otherwise, I'm not interested.
• ImageCombo Control
This solves a problem which a lot of VB programmers have asked for, putting
graphics in a list. It's more effort to program than a simple text list, but if you
want the graphics then it's the way to go.
• ImageList Control
I use the Toolbar control a lot! Since the Toolbar gets its images from this control,
then that means I have to give this one a thumbs up! I need it, I like it, and I use it
all the time.
• Internet Transfer Control
From what I've read, this is much improved over the version that came with VB5.
Many of my users are corporate employees from engineering areas. Their needs
rarely require an over-the-next solution so my experience on this one is minimal.
However, since it is the only internet control in VB, then by definition you will
use it if you have needs for Internet applications.
• ListView Control
The four controls - the listbox, the common dialog control, the TreeView and this
one (ListView) can pretty well handle display of data in simple or heirarchical
methods. It's a useful control, but not one that you cannot live without.
• MAPI Controls
This is an excellent example of a control which is very specialized, so much so
that no one I know uses it. I have no doubt someone does, but I just haven't met
them yet.
• Masked Edit Control
You'd think that this control would be one of the most popular there was and that
Microsoft would have made it an intrinsic control. But, it just didn't turn out that
way. The earlier versions of the control gave it a very bad reputation and it doesn't
seem to have recovered from it. It's not exactly the easiest to work with and the
actual operation isn't as trouble-free as I'd like. I don't use it but I think about it a
lot!
• MonthView Control
Calendars in a program out to be very useful. Every PIM has one so why haven't
my own applications had them? Maybe if I'd had this control in VB5 I'd be further
along the learning curve.
• MSChart Control
Yep - when I need a chart I use this one. Actually I don't like it all that much. It
has a huge number of properties and I never seem to get all of them working
together the way I want. Even so, it comes with VB and it can be made to do the
job, so I use it.
• Multimedia Control
As I mentioned, I mostly do engineering-oriented applications. The use of .wav
and .avi files would be fine, but for my needs I would want to create the .wav/.avi
files myself and VB has no means of doing so. If you can use stock files from
someone else, then this control is really a valuable tool. It's the only control in VB
that does what it does, so it must also be the best one!
• PictureClip Control
Multimedia presentations and applications really are great. But as all artists know
you can't just create a quality image in seconds. Having this control available to
house images is fine, but where do all those images come from? Like with the
Multimedia Control, this one is valuable to folks who have access to images that
already exist and which meet their own business needs.
• ProgressBar Control
This is the one where I am really delinquent. I owe it to my users to apply this
control much more often than I do. I recommend that you use it whenever
possible. The techniques of changing the cursor to an hourglass is good, but a
progress bar is much better!
• RichTextBox Control
This is very much a specialty control. For 99% of my user inputs, a simple text
input is just fine. I've gotten a lot of email from users who are using this control
so I know that the lure of better looking text must be hard to resist. However, I
resist it and don't really have any reason to recommend this one to you unless you
are writing some kind of word processor or if you really need to display formatted
text.
• Slider Control
Yawn. Well, maybe not. There are times when adjusting something to get a value
is needed. But I could do that with the intrinsic scrollbars already. This control is
easier to use but I wish Microsoft had spent their money getting a totally new
feature rather than a better old one.
• StatusBar Control
This one is an excellent way to give your user messages about the status of the
application or about the status of a user request. I don't know exactly why I don't
use it more, but I'm certain that my bad attitude will change. I recommend you
learn how to use this one and that you apply it to virtually every program you
write.
• SysInfo Control
Based on questions I get from users this one should be a big winner. There are all
kinds of reasons why a programmer needs to know about the PC on which his
.EXE is running. This control has made a good start in providing that kind of data
to an application. I'd rather have seen it built in to VB as functions but until then
you can use this control to get data that otherwise would require the use of the
Windows API.
• Tabbed Dialog Control
• TabStrip Control
• Toolbar Control
The Common Dialog box is easily the most useful ActiveX control, and the
Toolbar control takes second place. The control is reasonably easy to use and I've
never had any trouble with it - it works as advertised! I highly recommend you
learn to use this one.
• TreeView Control
Except for the lack of a built-in ability to save its content, this control has a lot of
application potential. I've used it or one of its predecessors in every version of VB
since VB3. Learn to use it right and it can provide a very strong user interface for
the display of ordered data. If you can't figure out how to save a tree structure,
email me and I'll let you in on the code I came up with.
• UpDown Control
Pretty simple, but actually pretty useful. It should have been intrinsic too, but it
isn't. You won't have to spend much time on it to become an expert so just learn it
and then put it on the shelf until you need it. You may not need it often but when
you need what it does, you'll be pleased that it is available.
• WinSock Control
I don't use it. However, lots of my visitor do ask questions about it and it seems to
be a pretty popular control. As soon as I bite the bullet and get more into Internet
programming I suspect this one will move up the list of favorites.
Summary
As I said, I tend to use a few controls often and a lot of controls very seldom. If I was an
expert in the controls I use infrequently, would I tend to use them more often? It's the old
problem of not knowing what you don't know. I plan to work on stretching my control
selection to give all of my less favorite controls a better chance. In a year, we'll see if my
list of favorites has changed!
Overview
It's worth noting that when managers talk about programmers, one of the common
metrics used to describe performance is "lines of code per month". There's all kinds of
debate about how good a metric this is, but the fact is that the metric is used!
It's not that you don't get credit for novel algorithms, or that you won't be a hero to fellow
programmers when they see how you solved a problem with 10 lines of code that took
them 100. You'll get that credit (and mental satisfaction, too!) but looking at the big
picture it's clear that the volume of code you can crank out will be the visible result of
your efforts!
Let's walk again through the elements of writing a VB application. The percentages at the
right are an estimate of how much time a programmer might spend on the various phases
of the program. For short programs, a greater percentage would be spent on the concept
and user interface phases. For larger programs, more time will likely be spent on the later
phases. However, in either case you can see that the coding section is one of the key areas
in which a programmer will be spending his time.
Get the picture? If you want to be a great programmer, you have to know how to
code!
There's another aspect to coding that you need to be aware of, but it's a little harder to
explain. In the electronics manufacturing business there's a saying that 90% of the cost of
a product is determined in the design. Can you see the link? Writing a program is
essentially a design task, aimed at solving a problem. Like most things, there are many
design approaches for every problem. Some solve the problem by grinding out an answer.
Some are very elegant. Others are so complex that even the designer has a hard time
keeping up with the convolutions of the approach.
Remember that in my Training/Advice I harped on the idea that a programmer's job was
to economically provide the result for which he is being paid. A customer will be more
impressed by a job done on time, on budget and which meets spec than he will be for a
project with overruns because of bells and whistles (or unusual code) which do not
improve the utility of the application to him or his employees.
As I go through the rest of the tutorial I'll try to show how these principals can be applied
to real life decisions and solutions.
Language Grouping - According to Beene
My overriding approach to learning is take what I read and try to piece it together with
everything else I've learned. I think of all knowledge as one big puzzle and it's important
to know where each piece of information goes in the puzzle in order to understand it's
importance. In programming, knowledge is certainly a tool and as my daddy used to say,
"It's the poor carpenter who blames his tool!".
The immediate value of this pearl of wisdom is shown in the following chart.
Beginner's who read through the Microsoft manuals, particularly the Language Reference
manual, are often intimidated by how darn many commands they find. An alphabetical
listing is simply no help in getting your arms around the problem. Back in the DOS days,
several of the BASIC manuals groups commands much like what you see in the table
above. This one is one that I did myself, while reading through the entire Microsoft
VB Language Reference!
The value of such a grouping is twofold. If I had it to start with then I could have "bitten"
off commands in small chunks. The small doses would consist of commands which act
together to let me perform categories of tasks (file I/O, user input, loops, string
manipulation, etc.).
Secondly, by creating my own grouping, I forced myself to think about the code and to
understand not only what the command can do, but how it can be used with other
commands to get a job done!
This brings me to another philosophical point. You noticed that I mentioned having read
the entire Language Reference? On my Beginner's page you may be noted that I also
have read the Programmer's Guide front to back not once, but three times? I am a staunch
believer that reading material can only be absorbed little by little. You read something
once and you get 70% of it. Read it again and you get up to 90%. Third time brings you
up to 95%. Better yet, write your own tutorial and you'll get some of that last percentage .
If you want to learn code, then you have to read the manual over and over til it makes
sense to you. Each time you learn something, you're better able to learn something else.
That's why rereading a manual is so valuable. The skills you pick up in the first reading
make it easier to understand the parts you didn't understand the first time. I encourage
you to read, read, read and while you're doing it, take notes and later summarize what
you've learned. It sounds tedious, but then coding is not exactly all glitter either!
All of you have seen the acronym RTFM, right? Well the popularity of this phrase just
backs up what I've been saying. You'll get no sympathy from me for misunderstanding a
topic unless you can show me where you studied the topic. Of course, it's okay to not
understand the manual's explanation of a topic (Microsoft's manual are good, but they are
definitely not great!) but you owe it to the person you're asking questions of to have done
the leg work yourself before drawing on their experience to help you out.
Variables
I know you have been getting anxious to get to the coding part which I keep referring to,
but there's one more lesson you need before we get there. The lesson is about variables.
Simply, a variable is a name you use in your program which refers to a value. You've
probably already seen variable names like x, or i, or name, or .....
You've probably already heard that values can be represented in many ways, such as
integers, floating point values, strings, objects, etc.
Here's the most important list of variable types you'll run across in VB:
This isn't the whole list, but it's definitely the ones you'll use 99% of the time in your
applications. I'll bring up the others as we need them in the tutorial.
This list is not just an exercise in useless knowledge. Later on you'll see how the use of a
particular variable type can be of use in speeding up your program or of how using the
wrong variable type can actually result in a wrong answer in some calculations! What
you don't know can really hurt you!
File I/O
Often, books on VB don't cover this topic until much later in the book. I'm covering it
early because it influences how I've grouped the VB language into the chart above.
A fundamental thing to understand is that computer files are usually stored in two basic
ways, ASCII and binary.
1. ASCII storage is most useful for storing strings. When both numbers and strings
are stored, ASCII is normally used. VB commands for ASCII file access are
usually the least complex I/O commands, but are not as flexible as binary file I/O
commands.
2. Binary storage is more useful for storing numbers. VB commands let you read
one or more bytes of binary data at a time and if provides more flexibility in
moving around through the file.
There are, of course, other schemes for storing data. Many programs such as Word,
Excel, and PowerPoint have their own storage schemes. This is also true of database
program files such as those created by Access or dBase. This tutorial won't discuss
proprietary formats except to note that they exist.
Printing
VB has commands which allow you to print information, either to the computer screen or
to a printer. For the printer, VB creates an empty "canvas" to which your commands
write, then dumps the "canvas" contents to the printer on demand or at the conclusion of
a program.
For me, the single most tedious aspect of coding is that of printing reports. I strongly
advise that whenever possible, that you make use of reporting tools such as the Crystal
Reports control that comes with Visual Basic. Crystal Reports provides a very fast
method of creating printed reports against data contained within Access databases, which
is native database format supported by Visual Basic.
Procedures
One fundamental aspect of VB which will become second nature to you is the idea of
procedures.
When we talk about VB commands, such as "Print", or "Open", we are talking about a
command which tells VB to run a section of code which performs the Print or Open
function. The code is contained in the various VB files that were installed on your
machine, such as DLL files that get distributed with your applications.
With VB, like most languages, you can create your own "commands" but we call them
procedures instead. The two types of procedures VB supports are called Subroutines and
Functions.
1. Functions: These procedures are a section of code which is run when the
Function is called, and a single value is returned to the calling line. For example,
when you use the square root function in VB:
x = SQR(25)
This is a VB function called SQR. It passes the value 25 to the function and the
function returns the square root and places it into x.
2. Subroutines: These procedures are just like a Function, but no value is returned.
It's important to note that procedure calls include a list of values (or variables) which are
passed to the procedure. The procedure is allowed to change those variables when it is
executed - but you make the decision by the choice of your code within the procedure.
Okay, let's begin to pick apart the subject of coding. You'll remember that I described
coding as something you put into an event procedure that VB will execute when the event
occurs? Well, that's true but you can also add code to your application which is not
contained in an event procedure, but which must be called from within those event
procedures.
Here's how it works. If you double-click on an object in the IDE you'll be presented with
the code window for that object. The upper left dropdown list shows the list of objects in
your application and the upper right list shows the events that each object supports! Its an
excellent way to explore the events your objects can support. If an event has had code
added to it, the event list make the event title bold.
If you look at the top of the left dropdown list, you'll see a listing that is labeled
"General". Remember those Function or Sub procedures we discussed earlier? Well you'll
find all of them in this "General" section. VB automatically collects all of the user-
defined function and sub procedures into this one area.
So, back to a higher level of discussion: When you enter code, you first think to put it in
the events of your project objects. If you have special function or sub procedures to write
(mostly because it will be used in multiple locations throughout your application) then
you create a Sub or Function to put the code. Sub/Function procedures work identically
except VB controls when an object event procedure is executed, whereas the code you
write in the event procedures can specifically call out for your custom Sub/Functions to
be executed.
By the way, you can also cause an object's event procedure to be executed at any time.
For example, if you have a button (Command1), then it's click procedure is
command1_click. If you type this procedure name in as a line of code, then it will
execute, just as though you have clicked the button with your mouse!
Helpful Tip!
Visual Basic has some built in variables which can make your code very easy to read, and
more importantly, are much easier to remember than the actual value of the variable.
Here's how it works:
Suppose you want to set the .CHECKED property of a checkbox to its checked state? If
you look into HELP you'll see that you must see the .CHECKED property to a value of
"2" for it to be checked. Easy enough? Well, consider across all the controls that there are
hundres of properties to remember. VB comes to the rescue with built-in variables. In our
example, you could set the .CHECKED property to the built-in variable VBCHECKED,
which VB will recognize as a "2".
As you would guess, there is also a VBUNCHECKED. Both of these are visually self-
explantory, whereas if you used an integer (2 or 1,in this case) you might trouble figuring
our which state the code is intended to create.
VB has a lot of these easy-to-remember constants. When you read HELP for the syntax
of a command/function, you will find the list of built-in constants which can be applied.
Get in the habit of using these built-in constants to avoid the hassle of memorizing the
actual values themselves!
In the earlier lesson you were introduced to coding, and reviewed a chart which groups
VB commands into useful categories. In this section of the tutorial, I take each one of the
commands and provide the syntax and a brief description of what the command does. For
details, you can turn to the VB HELP file. My intent is to allow you to skim quickly over
the commands to determine which one can help out in your situation. This page is kind of
long, but I wanted to keep it all on one page to make it easier for you get scroll through it.
I've also summarized the contents of this page in a command summary chart.
Operators
Here are the VB operators used to perform mathematical operations on one or more
variables. Aside from the normal multiply/add/substract and divide, you will find the
AND, OR, Not Equal, MOD and Integer Division operators very useful.
• / - Normal division
• \ - Integer division (truncates the answer)
• ^ - Exponentiation operator
• * - Multiply
• + - Plus
• - - Minus
• = - Equal
• > - Greater Than
• < - Less Than
• <> - Not Equal
• >= - Greater than or equal
• <= - Less than or equal
• AND - Defines a boolean value that is the AND of two values
o result = expression1 AND expression2
• OR - Defines a boolean value that is the OR of two values
o result = expression1 OR expression2
• XOR - Defines a boolean value that is the exclusive OR of two values
o result = expression1 XOR expression2
• NOT - Defines an opposite boolean value
o A = NOT B
• EQV - Performs a logical equivalence on two expressions (result is true if both
expressions are true)
o result = expression1 EQV expression2
• IMP - Performs a logical implication on two expressions
o result = expression1 IMP expression2
• IS - Determines if 2 variables reference the same object
o result = object1 IS object2
• LIKE - Determines if one string matches a pattern
o result = string LIKE pattern
• MOD - Returns the integer remainder of a division
o i = 27 MOD 5
Math
VB also provides built-in functions which can act on variables. Most are self-explanatory.
In my experience, the VAL, RND, and ROUND functions are among the most valuable,
so be sure to pay close attention to them!
Strings
In my experience these functions are used more than just about any of the other VB built-
in functions. The FORMAT, MID, and INSTR functions are incredibly powerful and I
use them extensively. If you don't understand what they are, they are worth the time to
figure out! The LEN and CHR functions are also valuable as are the variations on the
trim and case functions.
Arrays
Every programmer eventually uses arrays. Mostly they're pretty easy to understand. Take
note, however, that you can resize an array with REDIM without losing the data. For
details, see the PRESERVE keyword in the HELP entry on REDIM. If you use the
LBound/UBound in your code instead of hard-coding the dimension of the array, you can
later change the size of the array without touching your code!
Declarations
I probably get more questions about the functions in this section than about any other
group. In general, the concepts are pretty simple, but the details of getting it exactly right
can cause even experienced programmers trouble. Focus on understanding
Dim/ReDim/Public/Private/Sub/Function/Type and Set. However, they're all useful at
times, so bear down and commit these to memory. I'll try to add more text and tips on
these than I have on the others.
Date/Time
These functions are pretty self-explanatory so I've not added any extra comments
to them.
Miscellaneous
In this list you'll find some of the features of VB about which I get a lot of email
questions! The MsgBox is easily the most used of the bunch. It handles all of the
"Y/N" queries to your user so get to know it well. Also, the DoEvents, Shell, and
Command functions are indispensable in certain occasions so make sure you
know when they should be used.
o MsgBox - A built-in dialog box that gives a message and allows a user
input
i = msgbox "Read this!", vbokonly, "Test Message"
o DoEvents - Allows VB to complete pending tasks
doevents
o Shell - Executes a 2nd program from within the current program
shell "notepad.exe"
Note - VB does not wait for the Shell'd program to quit before
executing the next line of code!
o Command - Gives any text that followed a VB .EXE execution command
temp$ = command
o Environ - Returns the system environmental space content
temp$ = environ
o Beep - Makes the computer beep once.
beep
o InputBox - A built-in dialog box that allows entry of a text string
inputbox "Input a value!", 5
o AddressOf - Provides an entry point for an external program to use a
procedure
AddressOf ( procedurename )
o AppActivate - Activates an applications window
AppActivate ( windowtitle )
o RaiseEvent - Fires an event declared at module level
RaiseEvent ProcedureName
o Load - Load an object
load form1
o Unload - Unload an object
Unload form1
o LoadPicture - Load a picture into a control property
form1.picture = loadpicture (filename)
o SavePicture - Save a picture to a file
SavePicture(form1.picture,filename)
o LoadResData - Load the data from a resource file
LoadResData(index,format)
o LoadResString - Load a string from a resource file
LoadResString(index,format)
o SendKeys - Send keys to another app as though they were from the
keyboard
Sendkeys {DOWN}
o QBColor - Returns a value corresponding to the original QB values 0-15
form1.backcolor = QBcolor (12)
o RGB - Returns a color value by inputting the red, green, and blue parts
form1.backcolor = RGB (12,128,256)
o Me - Refers to the current object, usually the active form
print Me.caption
Registry
I've never quite understood why Microsoft got away from the use of an INI file.
The ability to use a simple text editor to resolve problems with a program's
settings was a key feature about INI files. Also, no matter how Windows crashed,
the INI file was protected.
Whining aside, VB has made it incredibly easy to access values in the registry.
The following VB functions are simple to use and there's hardly any excuse for
not taking advantage of them. One thing to remember is that the registry save
strings so if you're saving or reading numeric information then may have to do
some string manipulation with the results.
Special Values
There are some keywords in VB which take on special meaning. Their use can be
confusing at times, but you'll get used to the terminology as your programming
experience grows.
Financial Calculations
For those folks who want to use VB for performing routine investment
calcuations, VB provides a variety of functions. Personally, I use them very
infrequently, but I suspect they are used regularly by a lot of programmers. I've
never gotten a single question in the mail about these functions!
----------------------------------------- --------------------------
---
Declarations Date/Time
----------------------------------------- --------------------------
---
Sub Call Set Date MonthName
Function CallByName Let Time
WeekDayName
Dim PropertyGet Event Now Day
ReDim PropertySet ArrayName Timer Hour
Static PropertyLet Implements DateAdd Minute
Public Option Explicit Friend DateDiff Second
Private Option Private Enum DateSerial TimeSerial
Const Option Compare TypeName DateValue TimeValue
Declare Type...EndType VarType Year WeekDay
Is GetObject DefType... Month
CreateObject
GetAutoServerSettings
-----------------------------------------------------------------------
----
LOOPS AND CONDITIONAL
-----------------------------------------------------------------------
----
IIF For i=1 to j Step k If_Then_Else Select
Case
End - Case
Stop Next i If_Then Case
IS cond
Switch ElseIf_Then Case _
TO _
GoTo... While cond Else Case
Else
GoSub...Return - EndIF End
Select
On...GoSub Wend
On...GoTo
Choose Do While | Until cond For Each
With - -
Exit Function Loop While | Until cond Next
Exit Sub
Exit Do
Exit For
Tutorial: Visual Basic File Handling
The usual model for all computer programs is that a user inputs data and the computer
saves it. Okay, there's a lot more than that to a computer program, but the point is that
virtually every program is written to save data that is entered or data that is calculated by
the software itself. If you want to be an expert VB programmer then you'll need to know
a lot about how VB handles files - what is possible and what is not, plus how to do
something in the smallest code or in the least amount of time. To do this you need to
understand the file handling features which VB offers.
Because of their universally standard format, simple text files (also called sequential
files) are often used as the storage method for information. The old DOS Edit program
and the newer windows NotePad programs both create simple text files.
To simplify the handling of text files, Microsoft is working on a new set of features that
will be implemented in an ActiveX object (the FileSystemObject). Until then, file
handling will continue as the manual procedure that it is today.
The two statements you must use to access a text file are OPEN and CLOSE. Here's a
quick example:
In this example nothing was done but opening the file and closing it.
In this example, the code reads one line at a time, walking through the file until the end-
of-file (EOF) is true. The line of data (minus the carriage return / line feed characters) is
put into the string variable temp$. In your own applications you can save each line into
an array, or concatenate them into a single string variable, or any other processing you
want to do.
This next example shows how the text can be read as a single string variable and put into
a textbox control.
Note that I had to add back in the carriage return / line feed to maintain the same line
break as was in the original file. If you want the file to be read simply as a long string,
replace the vbcrlf with a space (" ") to keep separation between the word at the end of the
line and the word which starts the next line.fx
The examples so far were to read a text file. Here's an example for writing to a text file:
In this case, each PRINT operation goes to a different line in the text file (which means a
crlf character is inserted into the byte stream). The PRINT statement provides a variety of
options for putting the data into the output file. You can put all the data in one line,
separate each piece by one or more characters, or format the numbers as they are written.
The bottom line is that whatever is written to the file is written as text and when it's read
back your program must convert it to numbers as needed.
One more example will be worthwhile. Suppose the data consists of columns, and you
next to extract the numbers from those columns. How do you do it? Here's how it could
be done for the case of having 3 numbers per line, 1 in each ten columns:
One of the really great features of binary file access is that you can often avoid using the
VB database features. This is important because the distribution files for database access
are HUGE and I hate having to put them in my application distribution files.
Another especially nice feature of binary files is that you can PUT a complete user-
defined variable in a single statement, and recover it just as easily. This greatly simplifies
data storage in many cases.
Let's get right into some examples. To put data into a file, use this:
In this example, all we did was write three variables to the file. To read them back, use
this:
You'll notice that we didn't have to format the PUT or GET statements in any way.
Tutorial: Printing
Let's amend the computer program "model" which I gave in the tutorial section on file
handling. A computer program basically consists of a user who enters data, a file in
which the data (or calculated results) are stored, and a paper copy of the data. The printed
copy is usually formatted in such a way as to allow the user to make sense of the data.
The point of this short essay is that most users expect to be able to get a hard copy
(meaning a paper copy) of their data. They want it stored, but they also want to be able to
take the results away from the computer for subsequent review. Hence - printing! An
important fact is that how well the data is presented to the user can make or break the
success of the application. Learning to use the printing tools of VB is critical to your
success as a programmer.
The bad news with DOS BASIC was that you had to print one line at a time. You couldn't
print line 40, then go back to line 10. The really good news is that in Visual Basic, an
object known as the printer is available to you. The printer is like a work space to which
you can direct the output of print statements or the output of graphics statements. You
can send text/graphics output to the printer object in any order you want, then when
you're done you can tell Visual Basic to print the material to a physical printer.
The other good news about Visual Basic is that you can also "print" inside an
applications window (a form or a picture control) and Windows will handle the
movement of the printed output as you move windows around or as you move other
windows in front of the printed material. With DOS BASIC you had to handle all of that
yourself!
The (almost) bad news with Visual Basic printing is really a Windows issue. Although
there are non-proportional fonts (same width for each letter) in Windows, they really
don't look professional. So most folks program the print statements to use proportional
(different width for each letter, to enhance to display of the text) fonts. The downside to
this is that since each character is not the same width, you have to specify the X/Y
coordinates of the print location.
VB has some tools to make it a little easier than I make it sound, and the conveniences of
the printer object really do outweigh the inconvenience of handling proporational fonts.
Printing Surfaces
Ok, I've mentioned that in VB you can "print" to more than just a physical printer. In fact,
you can print to a form, to a picture control, to the DEBUG object (more on this in
another section) and also to any physical printer connected to your PC or to any shared
network printer to which your PC is connected.
Here's one of your first opportunities to see methods at work. Do you remember we
described methods as being commands within VB which act on a control? Well, printing
(by which I mean the output of text as well as the output of graphics) is a method that you
use with an object. Here are three examples:
form1.print "test"
picture1.print "test"
printer.print "test"
All three of these do the same basic thing, which is to print the word "test" to an object.
The first two print on-screen to a form (form1) and to a picture control (picture1). The
last prints to the printer object that I mentioned earlier.
In every case where a print method is used, the printing takes place at the current X/Y
position of the object. There are several ways by which VB determines the current X/Y
position of an object (this isn't the same as the .Top or .Left properties of an object, which
determine the positioning of a window on your screen). However, you can always
override VB by using code to set the current X/Y position. Here's the code for it:
form1.currentx = 25
picture1.currenty = 200
printer.currentx = 844
Notice that there are two properites .CurrentX and .CurrentY. You can set them using the
statements I just gave, or you can use them to return the current X/Y position as follows:
i = form1.currentX
j = form1.currentY
One complicating factor in VB that you'll just have to get used to is the concept of an
object's scale. You can set the scale of an object to pixels, twips, inches, centimeters,
points, character, and millimeters. The default value is twips (1440 twips is an inch).
Depending on the application, you can make a big difference in the code if you select a
scale to match the type of application you're writing.
For example, when you're doing graphics work it may be much better to deal in pixels. In
general, however, I've found that only the pixel, twips, and inches scales are necessary to
meet my own programming needs.
One final comment about the difference in printing on forms and picture controls versus
printer on the printer. With forms/controls, the printing takes place immediately. With the
printer, none of the information is sent to the printer until you use the .EndDoc method,
which tells VB you're done printing and to send all of the information on the the physical
printer.
I go into more detail about printing graphics in the next section of the tutorial.
Printing Tips
Now that you have some general ideas of how printing works, lets do some examples.
I've picked some of the examples because they provide tips on how to do some of the
most typical printing tasks you're likely to need.
printer.scalemode = vbinches
printer.currentx = 4.0
printer.currenty =1.0
Each line will print at the left side of the printer, and the printout will be four lines deep.
Print in columns
If you want to print starting in a column, then reposition currentx for each item to be
printed. This example prints at 1, 3, and 5 inches.
printer.scalemode = vbinches
printer.currentx = 1
printer.print "column1 data";
printer.currentx = 3
printer.print "column2 data";
printer.currentx = 5
Notice that the print statement ends with a ";", which directs VB to leave the
currentx/currenty values positioned at the location following the current print operation.
Summary Hopefully that examples give you an idea of the basic concepts of printing.
Head over to my control summary chart - available in Excel 97 and Excel 5.0 formats -
to see a complete listing of the properties and methods available to you.
Finally, just in case you don't go looking right away, please remember that you can set
the orientation of the printer with the .orientation property. This lets you switch between
landscape and portrait very easily within your code.
Introduction
If you want to run your VB program, you have two options. You can open the VB project
within the VB IDE and run it there. Or, you can compile the project into a .EXE file and
run that.
To give (or sell) your program to other people takes more effort. You cannot give them a
copy of VB6 (it's illegal). If they already have VB6 (or the same version as you have),
then you can simply give them the .EXE file and they can run the .EXE file just fine.
Usually, however, you cannot depend on your users having a copy of VB on their
machines. That being the case, you not only have to give them a copy of the .EXE file,
but also a copy of any VB required files which they don't have on their machine.
Microsoft allows you to distribute any such files as are required by the user to run your
distributed .EXE program. Note that the distributed files can only be used in the run time
program. Adding a distribution will not necessarily allow a user who has VB on his PC to
use those files (OCXs) in the IDE. More on that later.
The fact that a VB program requires the presence of other files to operate correctly is
really bad news because those extra files can be very large. As a worst case example, I've
written a VB VRML application called WinPlace whose distribution file measures
almost 10MB! That's a lot of diskettes, or else a lot of dowload time over a modem.
Many potential users of WinPlace won't try it simply because it will take too long to
download the installation files!
Every VB program requires the use of a 1.4MB file, msvbvm60.dll. That means that no
matter how small the .EXE file is that you create, that your minimum size for distribution
files is 1.4M. Often, a VB .EXE file is only a few hundred KBytes (100K - 400K), but at
those sizes you're automatically going to require at least two distribution diskettes.
Another "gotcha" that awaits within VB is that the addition of a single feature can cause
an easy multi-megabyte increase in the size of your distribution files. For example, add in
any database features to a VB program and you'll see the distribution file list go way up!.
It's hard to tell ahead of time how big your distribution file size is, so you pretty much
have to create the distribution files to know for sure.
In this section of the tutorial I'm not going to walk through an actual setup file creation.
The capability in VB is known as the "Package and Deployment Wizard" and it's
reasonably straightfoward to use, although you have very little control over the details of
the installation procedure.
The concept that a menu selection is really a control is a very valuable piece of
information because as you will see, the menu controls support properties and events, just
like any other controls you're used to seeing. What this means is that you can use the
experience you have in using controls to help understand menu operation.
What menus don't support are methods. If you didn't read through my control summary
spreadsheet you might not have noticed it, but controls may or may not implement all
three of the categories - events, methods, and properities. There's no rule that says you
have to support them all, and in some cases it's just not necessary. Menu controls are like
that. You'll see that properties and events are all you need.
Before we get into the menu editor, in which you can set properites of a menu control,
let's look at the complete list of menu control properties. It's not very long:
The bottom line for using menus is that you use the Menu Editor to create the menu
structure and to set the properties for each menu. Then you add code to each Click event
to perform whatever function you choose in response to a user selection of the menu
items.
Menu Editor
As you can see, the editor has two general sections. In the top half, you set the properties
(you saw a complete list of the properties above). In the bottom half you create the
heirarchical strucure of the menu.
Remember that menus are only associated with a form. No other control has a menu. VB
provides the built-in ability to manage the display of all of the menu items. You only
have to create the structure and let VB handle it from that point on.
Also note that each and every form in your application can have it's own menu. The
menus can be identical (same properties) or they may be different. It's entirely up to you.
Now. let's talk about each of the properties and see if there's some guidance on what to
use for the properities.
• Caption
Simply use the shortest name you can. Users hate long captions because they take
up to much space on the screen and reading them slows down using the menu.
Also, try to use a caption that doesn't have the same first letter as any other menu
caption. This will allow you to use the first letter of the control caption as the
shortcut - it makes it much easier for the user to remember!
• Name
While it can be anything, remember that the menu event will bear this name. I
always use a name that starts with mnu so that I can recognize the event
procedure as belonging to a menu control. For example, the File menu caption
usually is associated with a menu name of mnuFile.
• Checked
Menu items are either checked, or not. You can check it from within the menu
editor or by using code. For example, this code will cause a menu item to be
displayed with a small checkmark to it's left:
mnuFileOpen.checked = TRUE
• Visible
If you want to prevent a user from having access to a menu item, simply set the
visible property to FALSE. This will keep the user from even knowing that the
menu item ever existed.
mnuFileOpen.visible = FALSE
• Enabled
To allow the user to see the menu, but not to select it, set the enabled property to
FALSE:
mnuFileOpen.enabled = FALSE
• Index
If you give a menu (or any control) a non-zero index value, that makes it a
member of a control array. Control arrays are covered elsewhere in the tutorial,
but the bottom line is that you can use the Load function to add new menu items
at run time, but only if there is a menu control array created during design time.
This isn't something you'll do a lot of, but at least be aware that it is possible. On
the other hand, there are lots of times where non-menu control arrays are very
useful, so keep the idea of control arrays in your mind and we'll talk about how to
apply them elsewhere in the tutorial.
• Shortcut
Most users want to be able to invoke a menu item from the keyboard. This is the
property that defines the shortcut key strokes. When a shortcut is defined, you can
invoke the menu item from the keyboard, no matter how deep in the menu
structure the item is that you are calling.
• HelpContextID
Like any control, this allows you to refer to a specific topic in the application's
HELP file. Pressing F1 while the menu item is highlighted will call up this topic.
This is a useful technique, but mostly applies to HELP files you've written
yourself. It speeds up how quickly a user can drill through the HELP file to get to
information about a menu item. In my own applications, I seldom use this feature.
Lazy perhaps, but it's not that terrific a feature to warrant maintaining the
synchronization between an application and a continously changing HELP file.
• NegotiatePosition
When you embed an OLE object which has it's own menus you have to give
instructions on how to blend the form's menu and that of the embedded object.
Because I don't depend on my users having specific OLE-enabled applications
(such as Word, Excel, or others) I rarely use this feature. When you need it, it's
great, I just don't expect most programmers to need it.
• WindowList
Only for use in MDI applications, where you have multiple MDI windows open at
one time. This is another feature which is really great if you need it, but in my
own applications I rarely need it. In this case, even though I don't use it much
myself, you might want to give MDI windows a second look because of the
convenience they offer to users. Microsoft changed version 6.0 of VB to default
to MDI windows in its IDE because of user inputs which supported the change. I
still set my own IDE to the single window interface but you may find your own
tastes running differently.
To end this section of the tutorial, here's a few areas where special handling of menus
might make your program more user friendly.
You've seen applications which provide a list under the File menu, of files which have
been previously opened. There are two basic ways to do this, either by dynamically
adding controls (remember my comment about control arrays?) or by creating the list
during design and simply setting the caption and visible properties to reflect the most
recently used file names.
When I write applications, I use Registry Settings to store the most recent file names and
then set caption/visible properties of 4 or 5 pre-built menu items.
One of the user-friendly techniques you should put in your applications is the practice of
setting the visible property of menus to FALSE if the user is not allowed to use the menu.
For example, if a program allows a user to make a selection of objects in the window then
you might make visible a menu item to delete the selected items. However, if there are no
items selected, then you should set the visible property of the delete menu item to FALSE
because the user has nothing to delete.
The alternative is to set the enabled property of the unusable menu items to FALSE. The
user can still see the menu item but it will be grayed out and will not work correctly.
Unless you have specific reasons to keep it visible, my preference is to set the visible
properties to FALSE so as not to clutter up a user's screen.
PopUp Menus
You should use this capability of VB as much as possible. PopUp menus are a means of
providing a user with context sensitive menus - which are menus that provide only the
options which are likely to be used according to where on the screen the mouse is
located. Typically, the popup menu is activated by using the right mouse.
First of all, any menu that is to be a PopUp menu must not be visible. Once it's visible
setting is set to FALSE you can use it as a PopUp menu. Plus, you can have multiple
PopUp menus on the same form.
Secondly, the invisible menu must have sub-menus. You call the invisible menu and it's
visible sub-menus are displayed.
Here's the basic code for a PopUp menu. This example assumes that you have a menu
called "mnuTestPopUp" whose visible property is set to FALSE. Put this code in the
MouseUp event of a form (form1 in this example).
If Button = 2 then
form1.PopupMenu "mnuTestPopUp"
End If
You can put this code in the MouseUp event of any control, but the line of code must
read "form1.PopupMenu" because only forms have menus.
HELP Menu
When you create a program, the IDE allows you to define the .hlp file which is displayed
by WinHelp when you press F1. But be sure to include a Help menu on the top of your
form. Users will expect it. In that menu, you should include at least two selections -
"Contents" and "About". The contents should go to the contents section of the help file,
but the about selection is normally used to call up a small window which gives version
and author information about the program.
Also, put the Help menu at the far right of the menu selections. Your users are used to
seeing it there and they will expect to find it in the same place as all other Windows
programs that they use.
You'll notice that I have used the phrase "users will expect it" several times. Remember
that as a programmer you want users to feel comfortable using you program and you
don't want to force them to use a non-standard interface unless there is a clear advantage
to doing so. Bottom line is that for your users' sakes, you should stick with Windows
standards whenever you can!
So, there you have it. If you have any trouble with menus or needs some more examples,
the VB HELP file has some pretty good code examples to help you along.
In my beginner's section I state that a programmer's job is to get to the customer results as
quickly and efficiently as possible. Common Dialogs are a great way to abide by this
strategy.
VB provides a single .OCX file which contains the code for all 5 of the windows known
as the common dialogs. Without further ado, here are the five:
• Open
• Save As
• Color
• Font
• Print
Before we get into using each one, remember that the common dialog windows do not do
anything automatically. All they do is provide a way of asking your user some
questions and returning the answers to your application. You must write the code to use
the answers!
For example, if your application displays the Open common dialog and your user selects
a file name to open, absolutely nothing will happen. You have to write the code that
peforms the open functions. The Open common dialog box only provides an easy way for
you to ask the user which file he wants to open.
You could write a completely custom version of the Open common dialog, customizing it
to your specific needs. However, this can take considerable time and introduces code
which you must maintain. It's far better to use the proven common dialog window than to
invent something new every time!
The code for displaying a common dialog box couldn't be simpler. Simply use code to
invoke the appropriate Method of the common dialog object as follows:
• CommonDialog1.ShowOpen
The common dialog object also supports the .ShowSave, the .ShowColor, the .ShowFont
and the .ShowPrinter methods which cause the display of the corresponding common
dialog window.
A few other points are in order. If you look at my Control Summary Chart you'll see that
the common dialog control has properties which you can set in code before you display
the dialog windows. In this tutorial I don't discuss all of the possible settings. However
both the VB HELP files and the VB 6.0 Programmer's Guide provide sample code.
Be sure to take note of the fact that by default, when a user selects "Cancel" in a common
dialog window that a program error will occur. If you don't override this by setting the
.CancelError property, you'll have to include error detection code in the procedure which
invokes the display of the common dialog window.
Also take note that the common dialog control allows you to control the display of
various aspects of the window by setting the .Flags property. You really should read
through the HELP file's discussion of all of the options you can control using the .Flags
property. There's a lot of power in that one property and you can add some powerful
customization of your dialog windows if you use them fully.
Open Common Dialog Window
And last but not least, a common error seen when using the Font dialog window is due to
not setting the .Flags property. That property must be set (check HELP for allowed
settings) before the Fonts dialog window will display correctly. You'd think Microsoft
would have given it a default value, but as it is you must set the property!
Mouse Overview
There are actually two parts to being a "mouse" expert. The first part is simply using
mouse movements, including button clicks, in your program. You'll find that handling
mouse movements is very simple. Any VB programmer can learn to respond to the
movement of the mouse or the click of a mouse button.
The second part is using the built-in drag-and-drop features of VB. I cover drag and drop
in the next section of the tutorial.
Mouse Movement and Mouse Button Clicks
Incredible as it may sound, you only need to understand 3 events to become a
MouseMaster (ok, it's not as useful a title as an MSCD Engineer, but the title comes free
with completion of this tutorial!). The key to this simplicity is that a mouse is not an
object. It has no properties and it has no methods. The recognition of mouse activity
(move/click) is actually built into all of the other controls! If you look at the controls that
come with VB (or commercial controls) you'll see the following 3 events:
It doesn't take much examination to realize that the arguments for each mouse event are
exactly the same. This greatly simplifies our discussion here and makes your learning
process much simpler!
First, let's make sure we know what is going on inside VB. If you press and release a
mouse button, BOTH the MouseDown and MouseUp events will be executed, for the
control over which the mouse cursor is positioned. Make sure you understand that.
Mouse events happen for the control under the mouse. This is true even if, after pressing
a button, you move the mouse of a control before releasing the button. In that case the
MouseUp event still takes place for the control over which the mouse button was pressed.
One thing to note about the mouse events. While the MouseMove event will happen by
moving a mouse, it will also happen when you click a mouse button.
Remember also, that clicking a mouse button or moving a mouse does not automatically
make anything happen inside your program. Unless you write code that executes inside
the mouse up/down/move events, your program will ignore the mouse actions.
As you can see in the arguments of the mouse events, there are only 4 variables to
understand. Let's tackle each one now.
X and Y
These are the simplest of the arguments and are exactly what you think they are - the
position of the mouse within the control (or the form, if the mouse cursor is not over
a control). The only "trick" to remember is that X and Y are given in coordinates as
defined by the .ScaleMode property of the control or form. Check out the graphics part of
my tutorial for information on the ScaleMode property of an object.
The X and Y properties are simply information that you can use in your program. For
example, if you were to draw a circle inside a picture control, and wanted to know if the
mouse click took place inside the circle, you would examine X and Y to see if it falls
within the bound of the circle. What you do with the information is up to the code that
you chose to put into the event procedures.
In my experience, the X and Y are typically used to identify where to take an action, such
as where to create a graphic.
Button
The Button arguments actually can tell which of the three possible mouse button(s) are
pressed. The possibles values of Button are 0 through 7. The following code shows how
you would use Button to to figure out what is being pressed:
If you simply want to know if a particular button is being pressed, and don't care about
the state of any other button, then you can use this code:
In all my programs I use the press of a single button for my user interface. I can't think of
a single instance where I found it necessary to have my user press two buttons at once.
Here's one more point you should know. The MouseMove event does not take place for
each pixel that the mouse is moved. Instead, the number of events that takes place
depends on the operating speed of your PC and how loaded the processor is. The bottom
line is that while the frequency with which MouseMove events are generated is
reasonably high, you cannot depend on the event to take place any specific number of
times, nor at any specific interval of time.
Shift
As I mentioned above, I very rarely require that my user press multiple mouse buttons to
accomplish a task. I also never force him to press a key at the same time as he presses a
mouse button. However, there are a number of programs which do this (Windows 9x, for
example, uses CTRL-Mouse to identify a copy command). VB supports this capability by
providing the Shift argument. Like the Button argument, the Shift argument also has 8
values as follows:
One last point about using the mouse before we tackle drag and drop features. You saw
that the Button and Shift arguments take on values from 0 to 7. As I have mentioned
before I strongly suggest that you use the built-in constants that VB offers to help make
your code more readable.
If Button = vbLeftButton
For testing the Button argument, use the vbLeftButton, vbRightButton, and
vbMiddleButton constants.
Was that fun? Either way, what you just did was a drag and drop operation. How your
program responded to what you did was entirely up to the programmer of the application.
In programs which support drag and drop operations, the cursor changes to an icon
(indicating a drag operation is taking place) and when the mouse is released the icon
reverts back to a normal cursor (indicating that the drop operation is now over).
VB offers both an automated and a manual way to allow users to perform a drag and drop
operation. In either case, just like with common dialog windows, a drap and drop
operation is just a method of having a user give you instructions/data, which you must
use in code before anything happens.
The visible, outward sign of a drag and drop operation is the appearance and then
disappearance of an icon during the operation. However, if you don't have code in the
appropriate event, absolutely nothing else will take place in your application.
When the drag begins, the first object's does not experience an event. VB silently handles
the creation and movement of the drag icon. When the mouse is released, signalling a
drop operation, the DragDrop event of the receiving control is fired and any code in that
event is executed. If the DragDrop event has no code, then nothing else happens.
A second event is possible, which is the DragOver event. After a drag is initiated and at
the moment the drag icon is moved over another control, that control's DragOver event is
fired. It's only when the mouse button is released that the DragDrop event takes place on
the receiving control.
The dragdrop can be very useful, users know how to use it and users see it in most of the
popular shrinkwrap applications. With that background, how can you not put it into your
own application? Well, first of all, not every application can be made easier to use by
simply tossing in some drag and drop features. In my own experience, I use drag and
drop in only 1-2 out of ten programs I write. It has to add significant value to be worth
the time it takes to program.
There are only two event to worry about, the DragDrop and the DragOver, so it won't
take long to cover them both. In this example, the events of a form (Form1) are
examined:
Private Sub Form1_DragDrop(Source As Control, X As Single, Y As Single)
Private Sub Form1_DragOver(Source As Control, X As Single, Y As Single,
State As Integer)
Both events share the common arguments Source, X, and Y, whereas the DragOver
events includes the additional argument State.
• Source
This is a reference to the control which is being dragged. For example, if you drag
a command button onto a form, Source refers to the command button. You would
use Source.caption to refer to the caption of the command button. You can access
other properties or methods of the command button the same way, by using the
argument in place of the actual command button's name.
• X/Y
X and Y are the position at which the drop took place. You may use that
information in a variety of ways, but if it is used at all, it is typically used to
reposition the control from which the drag and drop operation began.
• State
An integer value corresponding to whether the dragged object is entering or
leaving the control or has simply moved its location within the control.
The only two properties of a control which affect a drag and drop operation are:
• Drag
The only method needed is appropriately called Drag. To use it, simply use code
such as:
• command1.drag
This will initiate a drag operation but as in the automatic case you still must write
any code that is executed when the drop action occurs.
Tutorial: Visual Basic Graphics Capabilities
In VB there are a limited number of graphics features, but mixed with the judicious use
of the Windows API a programmer can create some pretty fair graphics applications.
When VB falls short, there is also no shortage of third party OCXs which can step in and
add to the capabilites of VB.
I'll first walk through the graphical methods and properties which VB supports and then
discuss them one at a time to help you understand how they play together.
Scales
One of the first things about objects you need to undestand is the concept of scales. The
obvious question to ask about an object or graphic on a screen is "How big is it?". The
answer to the questions can depend on the units chosen for the measurement. Inches,
centimeters, millimeters, and pixels are all common units of measurement so you won't
be surprised to know that VB supports all of these. Their definition should be self-
explanatory.
VB also supports other units of measuring the size of something on the screen.
Specifically, it supports:
• Points
Points are the same as you're used to seeing associated with a font. 72 points
make an inch. Typically point sizes for typed text range from 10-12 for most
documents.
• Twips
Microsoft has also introduced a unit known as a twip, where there are 1440 twips
to the inch. The twip gives more resolution to measurements than the point (1
twip = 1/20 of a point), making possible more accurate graphics but still with
units tied back to the printing industry's standard unit of measurement, the point.
There are two properties available which help in converting units, the
twipsperpixelX and twipsperpixelY. Both can be used to convert from pixels to
twips. Both forms and the printer object support these two properties.
• Characters
Uses fixed twips (120 twips per horizontal character and 240 twips per vertical
character) definitions. This doesn't seem to get much use, but if you have some
great places where it provides an advantage, then I'd like to hear about it.
• User
In this case, the name "user" means user-defined. This is one of the most powerful
units you can use as a scale. Here, you define the number of units within the client
area (top to bottom is height, left to right is width). The advantage of this is that
you can use any size window with the exact same code! Sizing the window
simply sizes the graphics that you create.
ScaleMode
The ScaleMode property simply identifies which units are to be used. You can set it to
any of the units I've already discussed above. Once you pick a scalemode, VB adjusts the
size properties of the client area to match the selection.
A point to remember is that when you create graphics, you'll be creating them in the
client area of the window. In general, you'll be using an X/Y position within the client
area to direct VB to place graphics. The bounds of the client area are defined by the
properties ScaleWidth and ScaleHeight. VB also lets you pick the top/left starting
coordinates of the client area, using the properties ScaleTop and ScaleLeft. This can be
useful if you know that your graphics equation only apply to an area some distance away
from the coordinate origin (X=0 and Y=0).
• Circle
In this code, I simply draw 10 circles, progressively moving the center to the right
starting from the coordinate of X=500.
• For i = 1 to 1000 Step 100
• picture1.circle (i + 500, 1000), 400, vbGreen
• Next i
• Cls
It doesn't get any simpler:
• picture1.cls
The .cls methods will erase all graphics which have been drawn on the object, in
this case the picturebox.
• Line
Similar to the use of the circle method, this example simply creates 10 vertical
lines, positioned from left to right.
• For i = 1 to 1000 Step 100
• picture1.line (i+500,500)-(i+500,4000), vbBlue
• Next i
The line method can also draw boxes by simply adding an extra argument to the
code as follows:
The BF added at the end of the line of code simply tells VB to draw a filled box
instead of a line.
• PaintPicture
• Point
• i = picture1.point (100,500)
Here, the color of the point located at X=100 and Y=500 is assigned to the
variable i. In my own experience I haven't had any reason to use this method.
• Pset
This is the most basic drawing tool VB has to offer. With PSET you can set the
color of any point within the client area of the drawing surface. For example, the
next code randomly picks a color and randomly picks a coordinate at which to set
the color. For no good reason I limit the number of points plotted to 1000
• For i = 1 to 1000
• 'pick color value from 0 to 15 (the QBasic standard color
set)
• iColor = (Int(15*Rnd)+0)
• 'pick X from 0 to ScaleWidth
• X = (Int((Picture1.ScaleWidth * Rnd) + 0))
• 'pick Y from 0 to ScaleHeight
• Y = (Int((Picture1.ScaleHeight * Rnd) + 0))
• 'now plot the data
• picture1.pset (X,Y), QBColor(iColor)
• Next i
• Note: To get a value from n to 15, replace the "0" with the
value of n
With PSET you can do almost any graphic you can imagine, limited only by the
difficulty in controlling one point at a time. Also, the PSET method is not nearly
so fast as some of the higher order graphics methods.
In case it hasn't struck you yet, VB is not a graphics powerhouse. It's tools are very
simple and there's just not very many of them. However, all is not lost!
You'll find that to create graphics of any sophistication will involve the use of the
Windows API (Application Programmer's Interface), which are very powerful and very
fast. However, even though the API are fairly powerful, they are not designed to be a
graphics programmer's toolkit.
For that purpose, Microsoft has created another set of DLLs, known as DirectX. DirectX
was written for the more professional programmer who is looking to create the more
complicated, higher performance applications. You can get DirectX for free from
Microsoft.
DirectX works essentially the same way as do the Windows API. However my own
experience is very limited so all I can do is to point you off to the DirectX API and let
you experiment on your own.
It's amazingly hard for a programmer to figure out how a user will mis-use the program.
Actually, the term "mis-use" is not correct because the user will simply do whatever the
application allows him to do. If the programmer didn't anticipate a particular input that
can crash the program or if the programmer didn't anticipate a particular combination of
entries that could also crash the program, then shame on the programmer!
At a minimum, the programmer must allow for the possibility of an unknown error
occurring and providing a means within the code to respond to the error, giving the user
options to save (or not) any data already entered.
Contrary to the contempt some programmers have for non-technical users, it is not
acceptable practice to release programs which lose the user's data if he doesn't follow the
user's manual. This is especially true because often a user's manual is ambigous, or
written in techno-speak which the user might not understand.
It's also not acceptable to include in the user's manual an instruction that says "Don't do
this or the program will fail!". If the programmer knows of an input that will crash the
program, it's his responsibility to add the code to take care of the possible error condition.
In case you don't catch my drift here's my philosophy in a nutshell - It's the programmer's
job to create a program which can respond to any possible user input without crashing
and losing the user's data. You can whine all day long about how unskilled the users are,
but you might as well accept that some user somewhere will get careless and make a
weird combination of inputs that you didn't foresee. Under those conditions it is your job
to protect the user from his own actions. Fortunately, VB has the features which let you
provide this level of protection.
Errors
When you make an error in VB, such as a divide by zero, VB responds by stopping
execution of the program and will look for instructions in the code on what to do next. If
you don't include those instructions, the program will simply shut down. As I've said -
This is not good!
To respond to errors, VB provides the following code which turns on its error correction
options:
In case you don't remember, a label is a short word/phrase which ends in a colon
character, such as "BeginHere:". Any line can have a label. It goes at the start of the line
and does not interfere with any additional code on that line.
One thing to remember is that the On Error statement only turns on error trapping for the
procedure (Sub or Function) in which the code is found. You must use the On Error
statement in every Sub/Function for which you want error trapping to occur.
Here's a very sample bit of code to explain how error trapping works:
Sub TestProcedure()
On Error GoTo Label5
Value = 10 / BottomNumber
Exit Sub
Label5:
If BottomNumber = 0 Then BottomNumber = 1
Resume
End Sub
In this example, the On Error statement tells VB that if an error occurs, begin executing
the code which starts at the line labelled "Label5". In that code (for this example), if
BottomNumber is 0, an error will occur and execution starts with the "If" statement. That
statement will set the denominator to 1 if it was zero. The "Resume" statement will tell
VB to shift execution to the same line which gave the error in the first place! Now that
the denominator is changed, no error occurs and the Exit Sub procedure will execute
next.
Resume
The use of the statement "Resume" can take 3 forms:
• Resume
When VB hits a Resume statement in the error code, it will move execution to the
same line which caused the error, attempting to re-execute the line again. Be
careful here, because for this to work, your error code must have fixed the
problem that caused the error.
• Resume Next
When VB hits a "Resume Next" statement in the error code, it will move
execution to the line following the line of code which caused the error. This is
usually done when the error code does not, or cannot, correct the problem.
• Resume LabelX
In this case, VB is directed to a specific line within the current procedure. It can
any line you chose, usually chosen based on the specific error that occurred.
Generally, this approach is frowned on because it makes the code a little less
readable, but if it fits your needs then I wouldn't hesitate to use it.
Exit
Like an "Exit For" or an "Exit Do" statement, your code can direct VB to leave a
procedure at any time. In the example above, the "Exit Sub" is used to leave the Sub
procedure before the code following the line "Label5" is executed. This is a very typical
way of preventing the error code from being executed.
If you want your application to take no action at all when an error occurs then you simply
don't put any code behind the error label. In those cases, an "Exit Sub" is not necessary
because the "End Sub" will give the same result.
Err Object
To help out programmers, VB6 now provides a built-in object called "Err". On
occurrence of an error, VB fills the properties of the Err object with information that
uniquely identifies the error and with information that you can use in your code to figure
out what actions to take as a result of the error. A bit further in this tutorial, I list the
complete list of the Err object's properties and methods. It has no events.
The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub,
Exit Function, Exit Property or Resume Next statement within an error-handling routine.
Using any form of the Resume statement outside of an error-handling routine will not
reset the Err object's properties. The Clear method can be used to explicitly reset Err.
The Err object is a recent VB feature. In older versions the Error statement was available
(still is, for backward compatibility) and was used to have VB simulate an error. The
Err.Raise method is now the preferred approach.
For test purposes, you can even cause VB to simulate an error. To do so, use the Raise
method as described below.
• Description
• HelpContext
• HelpFile
• LastDLLError
• Number
• Source
• Clear
Provides an immediate clearing of all Err object properties. Strings are set to null and
numeric values are set to zero. You might choose to use it following the use of the
statement "On Error Resume Next" since the error information would no longer apply
The Clear method is called automatically whenever any of the following statements is
executed:
The value in clearing the Err properties is to make sure that any code which depends on
those properties doesn't see information from a previous error which has already be
responded to by code.
• Raise
If, in a procedure, an On Error statement is executed, then that error handler (the code at
the error handling label) is considered to be "enabled". If the On Error statement is
executed then when an error occurs, the error handler in that procedure is executed.
In a situation when a chain of called procedures exists (i.e., Procedure One calls
Procedure Two which calls Procedure Three), then when an error occurs VB will move
up the chain of procedures looking for the first enabled error handler it can find. If no
enabled error handler exists, VB will give an error message and terminate the program
(remember, this is bad!).
• Breakpoints
Easily the most common method of debugging code. When a line of code is
selected as a breakpoint, the program stops temporarily without losing the values
of variables. Once stopped, you can check/change values or even re-write code as
needed and then restart the program using those changes.
• Step Into/Over/Out
A close second, the Step options are valuable because it gives you the ability to
bypass blocks of code which you know to be good.
• Windows - Local/Immediate/Watch
Provides a more sophisticated way to monitor specific variables and to take action
based on the state/value of those variables.
• Single Line Execution
Once you have stopped a VB program, you can execute the code one line at a
time with this feature. It's a very methodical way to move through your program
and confirm that any logic/redirection code works as intended.
Bottom Line
Put error handling code in any application which you distribute to users. For your own
purposes you can choose to do without it but don't expect your users to pay the price of
your decision to deny them protection from errors. The VB IDE has some excellent tools
to help you analyze and debug code. You can prevent spending hours of time searching
for errors simply by understanding and using the built-in IDE capabilities.
Data Storage
Let's get to the bottom line quickly on databases in VB. Microsoft has gone to great pains
to add a lot of excellent methods for accessing data that is stored in not only Access
databases, but other database formats as well. For beginner's they've done an excellent
job! But even as I give praise to Microsoft for it's efforts, I can (and will) give you a few
reasons why not to use VB's database features. But even with its negatives, I still chose
to use database capabilities in a lot of my applications!
The huge penalty you pay for implementing those features is an enormous growth in the
size of the program that you must distribute. Simply by putting in a single data control on
a form, your distribution file size grows by over 5MBytes. Not only that, but database
handling within VB is not anywhere near as fast as users might like it to be. The penalty
you pay for features is a corresponding reduction in performance (i.e., speed)! But while
the penalty is not trivial, it is not so great as to prevent VB programmers everywhere
from using the VB data controls extensively.
Because of the negative aspects of using the VB database features, I look hard at my
programs and do not automatically use the database handling capabilities of VB until I'm
certain that the handling of the data by other means is not practical.
Another big negative of an Access database (or any other proprietary format) is the
inability to edit the file directly. If the file were simple text, you could edit it in a variety
of methods. In the proprietary format of Access you basically have to own another
Microsoft product to edit the contents of the database.
VB also allows you to work with databases entirely in code, using no controls at all. The
advantages to this are a greater level of control and faster performance. The penalty is
that you have to do operations manually (in code) that the controls might have
automatically done for you. I'll also cover this in more detail later.
Database Formats
While I don't use it all that much myself, VB also offers significant flexibility in the types
of databases it can access. The software industry has agreed upon a standard way of
accessing databases, known as ODBC (Open DataBase Connectivity). What this means
to you is that using VB you are not limited to those databases which come from
Microsoft. Even though the Micorosoft Access database format is an industry leader, VB
nonetheless includes the ability to access other formats such as FoxPro, DBase, and
others. You can even treat the contents of an Excel file or a text file as a database!
What is a Database?
While there are a lot of concepts you need to know to become an expert at working with
databases, here are three definitions with which you should start:
• Database
"A set of data related to a particular topic or purpose. A database contains tables
and can also contain queries and table relationships, as well as table and column
validation criteria."
• Table
"A table is a collection of data, arranged in rows and columns. For example, you
might have a table for author information called authors. Each column would
contain a certain type of information, such as the author's last name. Each row
would contain all the information about a specific author: first name, last name,
address, and so on."
• Recordset
"A logical set of records. where Microsoft defines a record as "A set of related
data about a person, place, event, or some other item. Table data is stored in
records (rows) in the database. Each record is composed of a set of related fields
(columns) - each field defining one attribute of information for the record. Taken
together, a record defines one specific unit of retrievable information in a
database."
In case you didn't catch the word "logical" in the definition of a recordset let me point it
out. It is very important! In dealing with databases, VB creates a temporary object called
a recordset, which contains the data (rows and columns) from one or more tables in the
database. The recordset is not the database, it is just a working copy of some or part of
the database tables.
Again, pay attention to the "some or part" comment. A recordset does not necessarily
contain the entire contents of a table within a database file. You can use SQL queries
(discussed elsewhere in my tutorial) to limit the recordset to selected records. Finally,
you should understand that the records in a recordset are in no particular order unless you
write code to order them.
In your VB code you can manipulate the contents of the recordset but the actual database
file will not be changed until you or the user take action to save the changes!
One final set of definitions which you should learn has to do with the types of recordsets
which VB can create for you. There are actually 5 types of recordsets you can create,
having to do with where the data can come from, how you can navigate through the
records, and whether you can edit the data in the recordset.
The type of recordset you use is very critical to get good performance from your
database application. Some recordset types take much fewer resources than others. Also,
some recordset types result in a 10X faster performance. The default values VB uses to
open recordsets are often not the best choice! Learn the differences and make a specific
selection in your own programs.
• Table-type Recordset
Basically a complete table from a database. You can use to add, change, or delete
records. This is the simplest in concept since it matches a complete table in the
database, but is not necessarily the best choice in many applications.
• Dynaset-type Recordset
The result of a query that can have updatable records. You can use to add, change,
or delete records. It can contain fields from one or more tables in a database.
Provides worse performance than a Table-type recordset.
• Snapshot-type Recordset
A read-only set of records that you can use to find data or generate reports. Can
contain fields from one or more tables in a database but can't be updated. Uses a
minimum of resources and provides fast performance.
• Forward-only-type Recordset
Identical to a snapshot except that no cursor is provided. You can only scroll
forward through records. This improves performance in situations where you only
need to make a single pass through a recordset.
• Dynamic-type Recordset
A query result set from one or more base tables in which you can add, change, or
delete records from a row-returning query. Further, records other users add,
delete, or edit in the base tables also appear in your Recordset.
While they all have their place, it's my experience that the first three are the most useful.
Accessing Databases
Remember that there are a variety of database products on the market, and that many
vendors have their own proprietary formats in which the data is stored. In the case of
Microsoft's Access database program, the method of accessing the database is through
software which Microsoft calls its Jet Database Engine. Other vendors have their own
access methods.
Many companies, including Microsoft, have provided their databases with the ability to
be read by software which uses a standard database manipulation method known as
ODBC (Open Database Connectivity). While a programmer can choose to let the VB
database-aware controls handle the details of accessing or manipulating databases
(recordsets), it is also possible to use code to create and edit databases.
Microsoft also offered a second data access interface to ODBC which had some
improved features over DAO, but which also lost some of the more general capabilities
of DAO. This approach, called RDO (Remote Data Objects), primarily targeted the more
complex aspects of stored procedures and result sets. It is generally not used by most
programmers.
Personally, I would like the choice of database access technology to be transparent to me.
However it's obvious that the Microsoft approach is still under flux and that
programmer's will need to be aware of multiple approaches for some time. This holds
true because the ADO features have just been introduced and have not yet matched the
DAO features of prior versions of VB.
For beginners, or any programmer who simply wants to put a data control on a form and
then display database information in other controls, the choice of ADO/DAO/RDO is not
critical because the controls handle it for you, The advantage in manipulating databases
in code is that you have a far greater degree of control over what actions are performed
against the databases.
VB Data Control
VB provides two controls which makes the link to the database file and which creates the
recordset that is exposed to the rest of the controls in your application. The two are
identical in concept but differ in the flexibilty they offer to the programmer. I'll discuss
the common features first and then cover some of the differences.
The concept of a data control is pretty simple. You set the .DataBaseName property to
tell the data control which database file to read. Then you set a .RecordSource property to
tell it which table within the file to make available as a recordset to other controls. As I've
mentioned earlier, you can also create recordsets which are combinations of one of more
tables by setting the .RecordSource property to an SQL statement.
For any controls which support databases, you set the .DataSource property to the data
control and the .DataField property to the specific field within the table/recordset that you
want bound to the control.
That's it! At that point the bound controls will display the information from the chosen
field of the recordset. If you make changes to the data then the database can be changed
to reflect the changes by either using the data control to move to a new record or by
executing the .Refresh method of the data control.
Ok, perhaps I simplify things a bit too much because there really are other properties
which a beginner must also be familiar with. But, it really can be pretty simple. You can
create entire database applications with essentially no coding, just the setting of control
properties.
If you didn't read my tutorial on SQL statements, then you've missed one of the most
useful database capabilities that VB has to offer. I won't repeat all of that section again,
but in a nutshell, you can set the .RecordSource to a command which tells the data
control to create a recordset that is a selected subset of the fields in one or more tables.
And there is lot more that you can do with SQL to reduce the amount of coding that you
have to write yourself. Every VB programmer should be familiar with the use of SQL to
create/manipulate recordsets. SQL can even be used to make mass changes to a recordset,
including search and replace actions. Take the time to read my SQL tutorial section and
to review the VB documentation on SQL. You'll use it the rest of your career!
Finally, we get to the actual list of the two data controls I mentioned.
In line with keeping your distribution files to a minimum, I suggest you use the intrinsic
control whenever possible. I haven't seen enough information about the ADO Data
Control to convince me that it's worth incorporating a separate ActiveX control into my
applications.
Data Bound Controls
Once you have the recordset available from the data control, you'll find VB to have a rich
variety of controls which can access the recordset. There are 7 intrinsic controls and 16
ActiveX controls which you have available to use. Each has its place and over time you'll
find yourself using most of them.
With the proliferation of controls, some of which are similar, Microsoft has created some
confusion. In particular, there are multiple versions of the combobox, list, and grid
controls. Let's try to address them first and then we'll get into the rest of the databound
controls. If you really don't want to worry about selecting between multiple options of the
controls, simply go with the latest version (DataList, DataCombo, and DataGrid) and
don't worry about the nuances between the various versions of the controls.
ComboBox
Here are the three versions that are available with VB, and some comments on how to
decide which one to use.
• ComboBox
This is the original, intrinsic, version of the control. Use it whenever possible to
keep down the size of your application.
• DataComboBox
This is Microsoft's most recent rendition of a combo control.
• DBCombo
Left over from VB5, you can forego using this one in favor of the newer
DataCombo control.
List
Here are the three versions that are available with VB, and some comments on how to
decide which one to use.
• ListBox
This is the original, intrinsic, version of the control.
• DataList
This is Microsoft's most recent rendition of a list control.
• DBList
Left over from VB5, you can forego using this one in favor of the newer DataList
control.
Grid
There are actually four versions of a grid control that come with VB, but only three of
them can be databound. Here are the three versions and some comments on how to decide
which one to use.
• DBGrid
The olders version that came with VB5. You'll have to find it on the VB CDROM
because it doesn't get automatically installed.
• FlexGrid
Also a VB5 version of the grid control. It does not support editing of the bound
data.
• Heirarchical FlexGrid
Newest version of the VB5 FlexGrid and still does not support editing of the
bound data.
• checkbox
• combobox
• data control
• image control
• label
• listbox
• picturebox
• textbox
Database Reporting
In the tutorial section on printing I lavished praise on how VB has made printing much
easier. In the area of creating and printing reports, VB6 has taken even greater steps to
simplify the programmers coding burden. There are now two options available to you
which can greatly simplify the amount of coding it takes to print data that resides in a
database.
In a prior version of VB a free version of a program called "Crystal Reports" was
provided. It included an OCX you could distribute with your applications. A Pro Version
was available commercially.
The magic of Crystal Reports was that you could create the report visually, in an IDE
similar in concept to the VB IDE. Once the report was created you could use code to tie a
database to it and then use code within your application to print (or preview) the report!
The version that came with VB wasn't as flexible as the Pro version but it meant that you
could create a professional-looking print report literally in a matter of minutes. Making
changes under this concept is an order of magnitude easier than it would be to make
changes in code which manually created the equivalent reports. I consider it an absolute
winner that VB programmers should take advantage of.
With VB6, Microsoft brought out their own version of a report writer. They include
Crystal Reports on the VB CDROM but it is not automatically loaded on your PC when
VB is installed. You can install it at any time by heading over to the
\common\tools\vb\crysrept directory of the VB CDROM and running the installation
program.
I've yet to use the built-in report writer. Once I do, I'll update this section to provide a
comparison.
Tutorial: SQL
To selectively display records in a recordset, the feature to use is SQL - Structured Query
Language. By creating a query (a text string which tells VB what to include in a recordset
or what actions to take against the data in a recordset) you can greatly simplify the code
you have to write in an application that utilizes databases. You can even write SQL
queries which will modify many records in a single operation. Once I understood the
basics, the use of SQL hit me like a revelation. It's easily one of the top 5 features of VB's
database handling capabilities!
Introduction
VB has very poor documentation of its support for SQL. What SQL is or how it is used is
a mystery for most beginners simply because it is so darned hard to find out any
information on the topic! Those few references to SQL that exist in the VB
documentation are very short examples and there is virtually no discussion on how to
create your own queries.
I assume that part of the reason for the Microsoft approach to SQL is that it sells a
product called SQL Server, which is a very powerful database interface. VB offers a
limited set of the SQL Server features but Microsoft doesn't highlight those capabilities,
preferring instead to sell its larger, more profitable product.
Considering the power of SQL statements I'm very surprised that Microsoft doesn't
highlight the features more than they do. However, the fact is that beginners have to look
hard to find help so that's where this tutorial comes into play.
Now that you've read some of the examples, how do you use them? Simply set the
RecordSource property of a data control to an SQL statement such as those above and
refresh the control like this:
Just make sure that any references to fields match those contained in the actual database.
Doing so will create a recordset whose content will match the constraints described by
the SQL statement.
Considering that there are entire books on this subject, I can hardly expect to do it serious
justice but there are some basics which can be summarized in a short tutorial like this
one.
First of all, there are 5 parts to an SQL statement which you should recognize:
Command Clauses Predicates Operators Aggregate Functions
Create From Distinct AND Avg
Drop Where Top OR Count
Alter Group By NOT Sum
Select Having Between Max
Insert Order By Like Min
Update In
Delete
With a little inspection you can pretty much guess what each of these pieces of an SQL
statement can do. However, here are a couple which you'll not want to miss and which I
use pretty regularly. Don't miss the last one in my list, which is a very easy way to sort a
recordset!
• Select
This is the most basic command which tells VB which fields to show in the
recordset.
• Delete
Simple, but very powerful means of deleting many records at one time.
• From
Defines the Table from which the fields will be extracted.
• Where
Precedes the conditions by which records are selected from the database
• Order By
Sorts the records by any combination of fields you chose.
This should get you started. Try out a few of the examples on one of the databases which
come with VB and you'll see that it's really very easy to use the power of SQL!
The left side of the screen is a list of code snippet titles. On the right side is the code
itself. In the lower left is a list of keywords that have been associated with each snippet of
code. Finally, there is a text box where you can type in a search string. CodeLib can
search through the titles, keywords, and code lines for the search string.
Before I get into the code, though, let's talk about the CodeLib program. When you're in
the VB IDE it's nice to be able to reach into a library somewhere and pull out a snippet of
code that adds a particular features to your own application. That's exactly what CodeLib
does. While you're in the VB IDE, start CodeLib also. It's window is kept reasonably
small so that it can be placed at the bottom of your screen, pretty much out of the way (or
you can simply minimize it).
When you need a code snippet, go to CodeLib and scroll through the available routines
by moving through the list on the left side of the screen. Once you find what you want,
simply click on the "Copy" menu selection and the entire multi-line code snippet will be
placed on the clipboard.
Then go back into the VB IDE, put the cursor where you want the code to go and use the
Windows paste command (Ctrl-V or Edit/Paste) to put the code snippet into IDE code
window.
You can also search through the code for any keyword/text string that you want, making
it easier to find the code you need.
I'll upgrade CodeLib over the next few months and provide additional features - but
always with an eye towards using CodeLib to demonstrate how to implement VB feature
options.
Of course, CodeLib also allows you to enter new snippet or to change the ones that are
already there. I use a second window for the edit screen to help demonstrate how to talk
between windows within an application.
Splash Screen
More often than not it takes several seconds for a VB application to load up all of the
files (EXE, DLLs, OCXs, and others) needed by the program. To entertain the user while
all that loading is going on, many VB programs first display a simple (fast-loading)
screen which draws the users attention. After a moment, once all the application's files
have been loaded, the VB application unloads the Splash screen and displays the main
screen of the application. CodeLib does this as well.
All it takes is a simple form with a graphics to entertain the user and a timer control
placed on the form. In CodeLib I set the timer interval for 1.5 seconds, at which time the
splash form unloads itself and then loads CodeLib's main form. The 1.5 seconds is
adequate for the user to actually look at the splash form, and long enough for the rest of
CodeLib to load, but not too long to bore the user.
You may have to experiment with the timer's interval setting on your own application to
determine how long the splash screen should be kept visible. Here's the code for the
Timer control event:
The concept of a control array is pretty sinple. Create two controls with example the same
name and VB will treat them as an array (VB forces you to give each one a unique
number, called an Index). When you click on any one control that is within a control
array VB will execute an event which is common to all of the controls within the control
array. VB also passes the Index value to the event procedure so that you know which
control was clicked.
The magic of this is that you don't have to repeat code for each array! Make sure you
caught this. You don't have to repeat the code!. In CodeLib, under the "Search" menu,
are the sub-menus "All", "Key", "Title", and "Code". Each is part of the same control
array and when you click on any one of them you see the exact same event procedure.
Then, within that event procedure, you only have to write code once which uses the Index
value to help determine what action you want to take.
In the case of CodeLib, I use code to check the selected item and un-select all others. I
also save the Index value in the Windows registry so that the next time I start CodeLib I
can restore the last setting.
Clipboard
The clipboard is a really great feature! It's the poor man's way of communicating between
programs and of making data available to other programs. And the really cool thing about
it is that it can handle graphics or text equally well! Believe me, that's a big benefit -
eliminating code you would otherwise have to write.
One of the most often used features of the clipboard is to simply copy text into the
clipboard's memory so that it can then be pasted into another program. With CodeLib,
that's exactly what happens. In many programs it is normal for you to have to select some
text and then use the Edit/Copy menu commands (or Ctrl-C) to copy the selected text.
With CodeLib I've opted to just have a single copy command in the menu which will
copy the entire code snippet, without the need for you to first select the code.
Microsoft has done a good job of keeping access to the clipboard simple. The code from
frmMain which puts the code snippets onto the clipboard is:
Once you have it in the clipboard, you can paste it into any other Windows program by
using Ctrl-V or by using the menu selections Edit/Paste. It's no more complicated than
that.
Registry
The ability to store data in the registry is analogous to storing project information into a
file. Previously, applications used a .INI file, which was a simple text file that stored
information the program would need the next time it ran.
For reasons that I have trouble appreciating, Microsoft has decided to get away from the
.INI file strategy and now goes with a "Master INI" file that they call the Registry. In lieu
of using individual .INI files, Microsoft encourages all application designers to put their
program-specifc data into the Registry. VB provides functions which can read/write
information into either the Registry or to a .INI file, so you still have freedom of choice.
Personally, I've been using the Registry simply because that means my users have fewer
files to worry about.
For your purposes, it's really not that critical whether a .INI file or the Registry is used to
store data. They both are transparent to the user of your application and both are
supported by VB. In general, I'd suggest going to the Registry approach because
Microsoft may yet decide to discontinue the .INI file features.
In case you don't appreciate what you could do with the Registry, take a look at this list:
In CodeLib I use the two simple functions that are all most folks need to save and retrieve
Registry information - "GetSetting" and "SaveSetting":
txtTitle = frmMain.lstTitles.List(frmMain.lstTitles.ListIndex)
In this example (found on the frmEdit) I set the value of a textbox called txtTitle. I fill it
with the content of a listbox on frmMain. All I have to do to access the listbox is to
precede the control name by the name of the form! So, the "frmMain." at the front
distinguishes between a control on the current form or on another form entirely!
frmAbout.show vbmodal
The next code listing is used in the load event of the About form to display. I keep the
credits in an external text file that I can easily change, and simply read the entire text file
into a textbox for viewing.
app.helpfile = filename
Once you set the HELP filename for an application pressing F1 will call up the HELP
file. You can also call up a HELP file by using the Windows API, by using the
CommonDialog Box, or by simply running the WinHelp EXE program that displays the
HELP files. In frmMain I use the following code to display the CodeLib HELP file:
Confirming an action
In the CodeLib menu is a Delete option. To prevent accidental deletions of a code snippet
I include the following statement in the click event of the menu control:
PopUp Menus
Creating a popup menu that appears when you right-mouse click an object is made easy
by the VB PopUpMenu function. In CodeLib, the main menu provides the following
code which provide popup menus with most of the controls on the form. The following
code is placed in the MouseDown event procedure:
Even more useful is that VB allows you to write variables of a User-Defined Type by
referencing only the variable name. You do not have to specifically list all of the sub-
elements to the user-defined type variable! This is very powerful so you'll want to review
my Save code.
This next code was taken from the Form_Load event of frmMain, and sets
the starting window position and size:
Search an array
There are many sophisticated ways to search through data. However, in CodeLib, the
library size is not very large and so I chose to simply walk through each and every entry
to see if I could find a match for the search string. There's nothing all that special about
my search routine. I do allow the user to chose whether to search the title, keywords, or
codelines for a search string. I make use of the INSTR function to do my string searching.
End Sub
Sort an array
There are many ways to sort a list or an array of data. I've used what is known as a bubble
sort. It's not very efficient but it is easy to code and for small lists it works quickly
enough not to be a problem. Here's the sort routine from frmMain:
'move all data down 1 position, unless the line to delete is the last
line
If lstTitles.ListIndex <> lstTitles.ListCount - 1 Then
For i = lstTitles.ListIndex To lstTitles.ListCount - 1
Code(i).title = Code(i + 1).title
Code(i).keywords = Code(i + 1).keywords
Code(i).CodeLines = Code(i + 1).CodeLines
Next i
End If
To Database or Not?
I plan to release a second version of CodeLib in a few weeks. The second version will not
be a replacement of this one. It will use VB database capabilities (versus the binary file
handling used in this version of CodeLib), and will be useful in showing how the
application of database features can both be helpful as well as cause problems in writing
and releasing an application.
CodeLib Revision History
There are a lot of Windows programs whose code is spread across multiple files. The
.EXE file does not always contain all of the code that a programmer might use. For
example, by creating his own library of procedures (usually in the form of a file with a
.DLL extension) a programmer can allow more than one of his applications to access the
same code.
Microsoft does a similar thing with Windows. There are many files which have code that
you can access, but the three most often named files are:
• user32.dll - controls the visible objects that you see on the screen
• gdi32 - home of most graphics oriented API
• kernel32.dll - provides access to low level operating system features
Later, I'll bring up some of the other files whose procedures you might want access.
However, there are some key issues which you should note before making a decision to
use an API call.
• Version Compatibility
Microsoft has long been known to update it's files without much fanfare - read
that as without telling anyone about it until it's already happened! And often, the
updated code may not perform exactly as did the older version. Users often find
this out by seeing unexected errors or by having their system crash and/or lock up
on them! In VB5 there were a huge number of programmer's who got bit by this
problem.
If you stick with the basic 3 OS files listed above, you won't see to much of this.
But the further away you go from the main 3 files, the more likely you are to get
into code which hasn't seen the testing and improvement cycle that the main
Windows OS files have gone through.
• File Size
One of the very major downsides to the concept of API is that all of this great
code lives in some very big files! Worse yet, sometimes the API you want are
spread over multiple files and you may be using only one or two procedures from
enormous files which have hundreds of procedures in them. Where this becomes a
problem is in a)load time - where it can takes several seconds to load the
procedure libraries, and b) - where you want to distribute your application and in
order to make sure that all of the procedure libraries are on your user's machine,
you have to put all of them into the distribute files. This can add many megabytes
of files to your distribution applications. It is a major problem for distribution of
software over the net, where 5 minutes per megabyte can deter a usage from
trying out an application just because he doesn't want to wait for the download!
• Documentation
Finding the documentation of what procedures are in a library and how to use
them can be very difficult. On my PC I have 3,380 files with a .DLL extension
with a total size of 539MB. That's a lot of code! Unfortunately I can count on one
hand the pages of documentation that I have to tell me what that code is or does!
You'll learn how to use DLLs in this tutorial, but without the documentation from
the creator of the DLLs you cannot use them successfully.
Despite these problems, the powerful magic of the API is that they are code which you
don't have to write. If you've read my Beginner's section you know that I am a big fan of
using 3rd party software to lighten my own programming load. As with 3rd party
controls, the API provide procedures which someone else wrote, debugged, and made
availble for you to benefit from. In the Windows DLLs files, there are literally thousands
of procedures. The key to API programming is learning which of these procedures are
useful and which ones you are unlikely to ever need! This tutorial tries to address just that
problem.
Getting Started It's actually simpler than you might imagine. By now, you've already
written procedures for your own VB programs. Using procedures from other files is
almost exactly the same as using procedures from within your own program.
The one big difference is that you must tell your application which file the procedure is
contained in. To do so, you must put 1 line of code into your VB program. And, you have
to do this for every external procedure that you plan to use. I suppose it would be nice for
VB to have the ability to find the procedures for you - but you can see that searching
through the 3,380 procedures on my PC might slow my applications down a lot!
Ok, let's get to an example. Telling VB about the procedure you want to use is known as
"declaring" the procedure, and (no surprise) it uses a statement which starts with the word
declare. Here's what a declaration looks like:
• "Declare"
This is reserved word that VB uses to begin a declaration. There is no alternative -
you have to use it.
• "Function"
Also a reserved word, but in this case it distinguishes between a SUB procedured
and a FUNCTION procedure. The API use Function procedures so that they can
return a value to indicate the results of the action. Although you can discard the
returned value, it's also possible to check the return value to determine that the
action was successfully completed. completed. alternative - you have to use it.
• "ExitWindowsEx"
Inside each DLL is a list of the procedures that it contains. Normally, in a VB
declaration statement you simply type in the name of the procedure just as it is
named in the DLL. Sometimes, the DLL true name of the procedure may be a
name that is illegal in VB. For those cases, VB allows you to put in the text string
"Alias NewProcedurename" right behind the filename. In this example, VB would
make a call to the procedure by using the name "NewProcedureName".
• "Lib 'user32'"
Here's where you tell VB which file the procedure is in. Normally you would put
"user32.dll", showing the extension of the procedure library. For the special case
of the three Windows system DLLs listed above, the API will recognize the files
when simply named "user32", "kernel32", and "gdi32" - without the DLL
extensions shown. In most other cases you must give the complete file name.
Unless the file is in the system PATH, you must also give the complete path to the
file.
• "(ByVal uFlags as Long ...)"
Exactly like your own procedures, Windows API functions can have a list of
arguments. However, while your VB procedures often use arguments passed by
reference (i.e., their values can be changed), most Windows API require that the
arguments be passed by value (i.e, a copy of the argument is passed to the DLL
and the originial variable cannot be changed).
Also, you'll note that a constant or variable is normally used as the argument for
an API call. It's technically acceptable to simply use a number for an argument
but it is common practice among experienced programmers to create constants (or
variables) whose name is easy to remember and then to use those in the argument
list. When you're reading or debugging your code later, the use of these easy to
read constant/variable names makes it much easier to figure out what went wrong!
• "as Long"
This is exactly like the code you use to create your own functions. Windows API
are functions which return values and you must define what type of variable is
returned.
While I make it sound simple (and it is), there are still issues which ought to concern you
when using the Windows API. Because the API code executes outside the VB program
itself, your own program is susceptable to error in the external procedure. If the external
procedure crashes, then your own program will crash as well. It is very common for an
API problem to freeze your system and force a reboot.
The biggest issue that VB programmers would see in this case is that any unsaved code
will be lost!. So remember the rule when using API - save often!
Because many of the DLLs you will use have been debugged extensively you probably
won't see many cases where the DLL crashes because of programming bug. Far more
frequently VB programmers will see a crash because they passed arguments to the
procedure which the procedure could not handle! For example, passing a string when an
integer was needed will likely crash the system. The DLLs don't include extensive
protection in order to keep their own code size small and fast.
It is simple to say that if you pass the correct type of argument, that you won't see API
crashes. However, the documentation is not always clear exactly what argument type is
needed, plus when writing code it is all too common to simply make a mistake!
Finally, it is the case that most of the DLLs you'll want to use were written in C++. The
significance of this is that the data types in C++ do not map cleanly into the data types
that are used in Visual Basic. Here are some of the issues which you need to be aware of:
• Issue1
• Issue2
Okay, stay with me just a bit longer and we'll get into the actual use of some API. But
first, here is a list of other DLLs which have procedures that could be of use to you.
These DLLs will show up later in this tutorial when we get to the API which I
recommend that you consider for use in your own applications.
• Advapi32.dll - Advanced API services including many security and Registry calls
• Comdlg32.dll - Common dialog API library
• Lz32.dll - 32-bit compression routines
• Mpr.dll - Multiple Provider Router library
• Netapi32.dll - 32-bit Network API library
• Shell32.dll - 32-bit Shell API library
• Version.dll - Version library
• Winmm.dll - Windows multimedia library
• Winspool.drv - Print spoolder interface
Often, the documentation that you might find for an API will be written for a C++
programmer. Here's a short table which helps you translate the C++ variable type
declaration to its equivalent in Visual Basic:
We're not quite ready to get into using the API. Here is a scattering of issues/comments
about using API which you will want to be aware of:
• Declare
o DECLARE in standard module are PUBLIC by default and be used
anywhere in your app
o DECLARE in any other module are PRIVATE to that module and MUST
BE marked PRIVATE
o Procedure names are CASE-SENSITIVE
o You cannot Declare a 16-bit API function in VB6
• ALIAS
o Is the "real" name of the procedure as found in the DLL
o If the API uses string, you MUST use ALIAS with "A" to specify the
correct character set (A=ANSI W=UNICODE)
o WinNT supports W, but Win95/Win98 do not
o Some DLLs have illegal VB name, so you must use ALIAS to rename the
procedure
o Can also be the ordinal number of the procedure
• Variable Type
o Very few DLLs recognize VARIANT
o ByRef is VB default
o Most DLLs expect ByVal
o In C documentation, C passes all arguments except arrays by value
o AS ANY can be used but it turns off all type checking
• Strings
o API generally require fixed length strings
o Pass string ByVal means passing pointer to first data byte in the string
o Pass string ByRef means passing memory address to another memory
addresss which refers to first data byte in the string
o Most DLLs expect LPSTR (ASCIIZ) strings (end in a null character),
which point to the first data byte
o VB Strings should be passed ByVal (in general)
o VB uses BSTR strings (header + data bytes) - BSTR is passed as a pointer
to the header
o DLL can modify data in a string variable that it receives as an argument -
WARNING: if returned value is longer than passed value, system error
occurs!
o Generally, API do not expect string buffers longer than 255 characters
o C & VB both treat a string array as an array of pointers to string data
o Most API require you to pass the length of the string and to fill the string
wih spaces
• Arrays
o Pass entire array by passing the first element of the array ByRef
o Pass individual elements of array just like any other variable
o If pass pass binary data to DLL, use array of Byte characters
• Callback Function
o Use AddressOf to pass a user-defined function that the DLL procedure can
use
o Must have specific set of arguments, AS DEFINED by the API procedure
o Procedure MUST be in a .BAS module
o Passed procedure must be As Any or As Long
• Passing a null value
o To pass a null value - zero-length string ("") will not work
o To pass a null value - use vbNullString
o To pass a null value - change Type to Long and then use 0&
• Window Handle
o A handle is simply a number assigned by Windows to each window
o In VB, the handle is the same as the property hWnd
o Handles are always Long variable types
• Callbacks
o Some API can run one of you own VB functions. Your VB function is
called a "Callback"
o VB supports callbacks with a function "AddressOf", which give the API
the location of the function to execute
o Callback functions must be in a module. They cannot be in a form.
• Subclassing
o All windows work by processing messages from the Windows operating
system
o You can change how a window responds to a message by intercepting the
message
o To intercept a message, use the API SetWindowsLong
• Miscellaneous
o Control properties MUST be passed by value (use intermediate value to
pass ByRef)
o Handles - always declare as ByVal Long
o Variant - to pass Variant to argument that is not a Variant type, pass the
Variant data ByVal
o UDT - cannot be passed except as ByRef
In case you don't know, VB6 comes with a tool to help you use API in your own
applications. The API Viewer is installed automatically with VB, and to use it go to the
Start/Programs/VB/Tools menu and select "API Viewer". The viewer actions much like
my own VB Information Center Code Librarian in that you can browse through the
various API, select one for copying to the clipboard, and then paste the declaration into
your own application's code window. You'll definitely want to try this out. The data file
that comes with the viewer if very extensive, listing 1550 API Declarations.
In my case I use API regularly, but I've never come close to using 1550 API. At best, I
barely have broken the 100 mark. It seems that for the most part I can get VB to do
whatever task I want without resorting to the API. However, in some cases you just can
do any better than a few lines of API code to get the job done! So, here's my own list of
useful tasks and the API needed to perform them:
Play sound Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" (ByV
Result = sndPlaySound (SoundFile, 1)
Run associated EXE Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal
List window handles Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, B
Find prior instance of EXE Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpC
Draw dotted rectangle Declare Function DrawFocusRect Lib "user32" Alias "DrawFocusRect" (ByVal
Invert colors of rectangle Declare Function InvertRect Lib "user32" Alias "InvertRect" (ByVal hdc As Lo
Get cursor position Declare Function GetCursorPos Lib "user32" Alias "GetCursorPos" (lpPoint As
Always on top Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" (ByVal h
Send messages to a window Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hw
Text alignment Declare Function GetTextAlign Lib "gdi32" Alias "GetTextAlign" (ByVal hdc
Declare Function SetTextAlign Lib "gdi32" Alias "SetTextAlign" (ByVal hdc A
Flash a title bar Declare Function FlashWindow Lib "user32" Alias "FlashWindow" (ByVal hw
Manipulate bitmaps Declare Function BitBlt Lib "gdi32" Alias "BitBlt" (ByVal hDestDC As Long,
Declare Function PatBlt Lib "gdi32" Alias "PatBlt" (ByVal hdc As Long, ByVa
Declare Function StretchBlt Lib "gdi32" Alias "StretchBlt" (ByVal hdc As Lon
ByVal dwRop As Long) As Long
Declare Function CreateCompatibleBitmap Lib "gdi32" Alias "CreateCompatib
Declare Function CreateCompatibleDC Lib "gdi32" Alias "CreateCompatibleD
Get window information Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (By
Declare Function GetParent Lib "user32" Alias "GetParent" (ByVal hwnd As L
Identify window at cursor Declare Function WindowFromPoint Lib "user32" Alias "WindowFromPoint" (
Drawing functions Declare Function MoveToEx Lib "gdi32" Alias "MoveToEx" (ByVal hdc As L
Declare Function LineTo Lib "gdi32" Alias "LineTo" (ByVal hdc As Long, ByV
Declare Function Ellipse Lib "gdi32" Alias "Ellipse" (ByVal hdc As Long, ByV
Get icon Declare Function ExtractIcon Lib "shell32.dll" Alias "ExtractIconA" (ByVal hInst As L
Screen capture Declare Function SetCapture Lib "user32" Alias "SetCapture" (ByVal hwnd As
Declare Function CreateDC Lib "gdi32" Alias "CreateDCA" (ByVal lpDriverN
Declare Function DeleteDC Lib "gdi32" Alias "DeleteDC" (ByVal hdc As Long
Declare Function BitBlt Lib "gdi32" Alias "BitBlt" (ByVal hDestDC As Long,
Declare Function ReleaseCapture Lib "user32" Alias "ReleaseCapture" () As Lo
Declare Function ClientToScreen Lib "user32" Alias "ClientToScreen" (ByVal
Get user name Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (By
Get computer name Declare Function GetComputerName Lib "kernel32" Alias "GetComputerName
Get volume name/serial# Declare Function GetVolumeInformation Lib "kernel32" Alias "GetVolumeInfo
lpFileSystemFlags As Long, ByVal lpFileSystemNameBuffer As String, ByVal
Identify drive type Declare Function GetDriveType Lib "kernel32" Alias "GetDriveTypeA" (ByVa
Get free space Declare Function GetDiskFreeSpace Lib "kernel32" Alias "GetDiskFreeSpaceA
Put icon in system tray Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (B
Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (B
Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (By
Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias " Shell_NotifyIconA
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destinatio
Declare Function DrawEdge Lib "user32" Alias "DrawEdge" (ByVal hdc As Lo
Wait for program to stop Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal
dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory A
Declare Function WaitForSingleObject Lib "kernel32" Alias "WaitForSingleOb
Hopefully, this section of the tutorial has sparked some excitement! You should now see
that a door of tremendous proportions has been opened to you. You've begun to leave the
limitations of VB behind and joined the rest of the programming community who have
already been using the API for years. I hope to add quite a bit to this tutorial section so
check back often over the next few weeks.
In case you have any question about the value of objects, let me state without reservation,
that objects (in the form of controls) are the single biggest reason why VB has been
so successful. In more recent versions of VB, Microsoft has expanded the object features
of VB, making it even more powerful than ever.
The availability of powerful tools does not automatically guarantee success. From my
viewpoint, the jury is still out on how useful these newer features are going to be for the
average programmer! I have no doubts about the power of the newer tools, but just like
70% of Excel/Word capabilities are never applied by users, so too are many of VB's
object-oriented features going unused by most programmers.
VB is known for its ability to allow a programmer to quickly, and easily, create a
Windows program. In part, this is possible because objects provide code which you
don't have to write! I cannot say this with enough force! Objects are written by
programmers to provide certain capabilities which you can access by executing the code
with the objects. In a way, this makes objects just another way of creating a code library -
similar in function to the use of API that you learned in the last tutorial!
However, don't mistake my simple comparison to imply that objects are as easy to use as
are the API. They're not! You'll spend a lot more time studying how to work with objects.
Mastering how to use API is a one-day session, with additional time spent on figuring out
which API to use. Learning to master the use of objects, however, is going to be one of
the major study tasks that you undertake in VB.
Some parts of objects usage are actually pretty simple. Some, however, are very complex.
In this tutorial we'll work our way up from the simple to the difficult.
You'll have to make a personal assessment as to the extent to which you implement the
range of object-oriented capabilities that VB offers. You may find that your applications
work fine with just the use of the basic controls that come with VB or by using the
Windows API when VB falls short. You may also find that you cannot get the
functionality from you want from your application or that you cannot reach the level of
efficiency at creating applications without depending heavily on objects.
In the end, I suggest that the criteria for using objects is whether they help you get the job
done with less effort than it would take to do the job without them! My personal
experience is that limited application of object programming is adequate to do just about
anything I need to do. I'll admit that I'm having trouble relating my own experience with
the object-intensive media blitz that you see in the VB magazines today.
There's an old saying that to someone with a hammer, everything looks like a nail! The
moral to the story is that you should develop skills with new tools in order to evaluate
which one applies to certain jobs. Let's begin that development right now!
Examples are an easy way for you to understand what VB treats as object:
These are all examples of objects to which you should have already been exposed as part
of your VB training.
The data inside an object is known as the properties of the object. In familiar terms, it
corresponds to the values of variables which are stored inside the object. For example, all
objects have names. The name is one of the properties of the object and the way that you
access a property in code is as follows:
tempString = ObjectName.Name
In this simple example, a variable called "tempString" is filled with the Name of an
object. All properties of objects work exactly the same way, using what is called the
"dot" notation. Here are some more examples:
h = Form1.height
w = listbox1.fontname
r = textbox.backcolor
g = timer1.interval
In each of these examples, a variable on the left is assigned the value of the property on
the right. The format for identifying the property name is also done the same in every
case - "objectname.propertyname".
Typically, whoever creates the object "exposes" properties which you can access. In the
VB IDE environment you can click on a control and the properties box (press F4) will
display all of the property names along with possible values for those properties. Object
properties are just like variable in that they can have a type. They can be integer, string,
dates, or any other VB data type. So remember when assigning property values to
variables that the VB rules for type conversion must be taken into consideration.
When in the IDE code windows, VB also provides a big help in remembering the
properties of an object. Once you've type in the object name and the ".", VB will display
a dropdown listbox which give all of the available properties.
Two other nuances about properties will be of interest. First of all, not all properties of an
object are "exposed" for use in your VB program. When we get around to creating our
own objects in code, you'll find that you can choose whether to expose a property for use
in code, or whether to keep it hidden within the object (so as not to allow its value to get
changed).
Also, ... (author mind block - as soon as I remember the other nuance, I'll put it here ).
Exposed objects cannot, however, be distributed with your application. If you plan to
create an application which uses exposed objects from a second application, then your
user must have that second application installed on his PC. This is not a trivial problem.
Unless you have some control over the user's environment you'll find it best to distribute
stand-alone applications - ones which do not assume that any particular software is
resident on your user's PCs.
All controls, whether in the form of ActiveX Controls (.OCX files) or in the form of
exposed objects, must be registered with Windows (as part of the Registry) before your
VB program can use the object. In the VB IDE you can call up the Components Dialog
Box which will list all of the objects (ActiveX files or exposed objects) thtat are available
for your use. If you select one of the objects for use, the object will appear on your VB
IDE toolbox and can then be used just like any of the intrinsic controls that you have
already used.
There is a utility called regsvr32.exe that comes with Windows which you will find very
useful. Regsvr32 allows you to manually register an OCX in the registry. The need to do
this manually can arise for a variety of reasons, but mostly because an installation
program failed to automatically make the registration. The code to register an OCX file
is:
regsvr32 filename.ocx
You can do this from a DOS command line or through the Start/Run menu option.
Classes
We're just about to get into the How of creating objects, but one more topic needs
discussion first. Before an object can be created, an object template must first be created.
Once that template is created a copy can be created. It's the copy with which you will
work in your VB programs.
In VB terminology, the template is called a class and the copies of the template are called
instances. In the registration process that we just discussed, it is the template, or class, of
an object that gets registered with Windows.
Object Browser
VB provides a tool with which you can browse all registered objects, including the
properties and methods which they expose. The Object Browser window can be
displayed by pressing F2 within the VB IDE. One advantage of the Object Browser over
the properites window is that the browser can show both properties and methods of the
registered classes. Additionally, the browser shows all registered objects, including the
objects exposed by applications that you have installed on your PC. It's the poor man's
documentation of all usable classes on your PC!
• References
It is possible use the DIM function to create a variable whose type is that of any
registered class. To do so, use this code:
• Dim X as ListBox
Variables which have been defined as an object type are useful because they can
be made to refer to an existing object. For example, this code, when used with the
line of code just given, associates X with the ListBox1 control.
Set X = ListBox1
Notice the use of the Set statement? To establish a variable reference to an object,
you cannot simply use the equal sign. You must use the SET statement.
There are several reasons why you should be interested in creating a second
reference to a control.
First of all, once the variable is set to reference the control, all of the control's
properties and methods and be accessed as follows:
X.name
is the same as
ListBox1.name
If nothing else, using variables rather than the full name of the control can save
you some typing as you write your code.
However there are other, more pressing reasons why the use of object variables in
code is valuable. Later, we'll get into the idea of Collections, which represent a
way to group objects so that you can address them one by one in code. It's similar
to the concept of an array of objects, but the code for accessing a collection is
different. I bring it up now because the following code for walking through a
collection of objects demonstrates why the use of object variables is so valuable
in VB:
Dim X as Control
For Each X in Form1.Controls
If X.Top > 500 then
MSGBox "It is below the line"
End If
Next X
What this code does is to walk through all controls on Form1 (the Controls
collection) and see if the top of the control is below the position 500. The magic
to this code is that the object variable X was successively assigned a reference to
every control on the form, and we could access the Top property of each control
simply by using the variable X! Otherwise we would have had to put code which
specifically named every single control and evaluated its Top property. The use of
an object variable made it possible to significantly reduce the amount of coding
that I had to do!
There is a variation on the use of the Set statement which you should learn, and
that is the Keyword "New". Elsewhere in these tutorials we
• Collections
VB also supports an object know as a collection. A collection object is exactly
what the name implies - a group of objects whose properties can be addressed
through code. And as the example above showed, it is not necessary to code the
individual names of each member of the collection.
VB provides the fairly simple means of working with collections. A collection has
only one property, which is "Count", the number of objects in the collection.
When an object is added to a collection it is given an index, with the first object
index starting at zero. To address an object in a collection you can use either it's
name, or its index as follows:
o Add
Allows you to add members to a collection.Optional. One thing to note is
that when you add a member to a collection you can give it a unique string
(a key) that can be used, instead of a positional index, to access that
member in the future.
o Remove
Allows you to remove members from a collection, either by specifying the
index number of the object or its key.
o Item
Returns a specific member of a collection, either by numer or by key.
Finally the loop construct I gave above is worth repeating because you can now
see how it applies to collections.
Dim X as Control
For Each X in Form1.Controls
If X.Top > 500 then
MSGBox "It is below the line"
End If
Next X
The "For Each" structure provde the ability to walk through every member of a
collection ("Controls" in this example) and then operate on each member as your
code/application requires.
As you'll see collections have become an integral and important part of the VB
coding environment. The example I just gave shows that using a collection (VB
built-in collections managed by VB or collections which you can create yourself)
can save you a lot of time and effort.
The old Texas saying "If you don't own an oil well, then get one!" very much
applies to collections. Not only can you save coding time and effort as I showed
in the example, but you'll find that even the controls which comes with VB
contain collections of their own. Whether you want to or not, collections are one
area where you'll be forced into learning about them simply because they are
becoming an integral part of the daily controls that you use.
• Class Modules
What we've discussed so far was perhaps the easier part of the tutorial. The real
power that Microsoft has added with VB5 and VB6 has to do with the ability to
create your own objects, including objects which you can expose to other
applications and which you can compile separately and re-use in other
applications.