Sei sulla pagina 1di 13

INTRODUCING VISUAL BASIC

1
What is Visual Basic?

Visual Basic is educed from the BASIC programming language. Visual Basic is a distinctly different language
providing powerful features such as graphical user interfaces, event handling, object-oriented features,
structured programming, and much more. Visual Basic programs are created in an Integrated Development
Environment (IDE). An IDE allows the programmer to create and debug Visual Basic programs conveniently.

Visual Basic is an object-oriented programming development system for creating applications under any of
the Microsoft Windows environments. It has the following two major components:

1. An extensive collection of prewritten tools, called controls. These controls are accessible as icons
within a graphical programming environment for creating customized windows components (e.g.,
menus, dialog boxes, text boxes, slide bars, etc.).
2. A complete set of program commands, derived from Microsoft’s implementation of the classical
BASIC programming language. The command set includes features that embrace modern-day
programming practices.

The overall approach to Visual Basic programming is two-fold:

1. Create a user interface that is appropriate to the particular application at hand.


2. Add a group of Basic instructions to carry out the actions associated with each of the controls.

Events and Event-Procedure

In traditional computer programs, the actions are carried out in a prescribed order. This order may be
sequential, corresponding to the order in which the instructions have been specified. In either case, the
order of execution is determined internally within the program.

Visual Basic, on the other hand, is based upon an event-driven paradigm, in which each feature included
within the program is activated only when the user responds to a corresponding object (i.e., an icon, a
checkbox, an option button, a menu selection, etc.) within the user interface. The program’s response to an
action taken by the user is referred to as an event. An event is a signal that informs an application that
something important has occurred. It is an action which you can respond to, or “handle” in code. Events can
be generated by a user action, such as clicking the mouse or pressing a key; by program code; or by
system. Note that the user initiates the event, but it is the program’s response that actually defines the
event. The group of Basic commands that brings about this response is called an event-procedure.

Event-procedures are Visual Basic procedures that respond to events and are automatically generated by
the Visual Basic. The programmer adds code to respond to specific events, and only events that are
relevant to a program need be coded.

Object-Related Concepts

In addition to events and event-procedures, you must understand the meaning of each of the following
terms:

FORMS. In Visual Basic, a window is called a form. Each form includes a title bar at the top. A form may
also include a menu bar, a status bar, one or more toolbars, etc. Some applications are based upon a single
form, while others require two or more forms.

Information and Communication Technology Department 1


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
CONTROLS. The icons with which the user interacts are called controls. Commonly used controls include
command buttons, option buttons, checkbox, labels, textboxes, and menus. The user will typically activate a
control (e.g., click a command button) to produce an event.

OBJECTS. Forms and controls are referred to collectively as objects. Most objects are associated with
events; hence, objects may include their own unique event procedure. Objects are also associated with their
own properties and methods.

PROPERTIES. Objects include properties that generally define their appearance or behavior. The choice or
properties depends on the type of object. For example, the name, caption, height, width, background color,
location and font are some of the more common properties associated with a command button.

Common properties of Visual Basic controls:

Property Description

Left The position of the left side of a control with respect to its container.

Top The position of the top of a control with respect to its container.

Height A control’s height.

Width A control’s width.

Name The string value used to refer to a control.

Enabled The Boolean (true/false) value that determines whether users can manipulate the control.

Visible The Boolean (true/false) value that determines whether users can see the control.

METHODS. Some objects also include special program statements called methods. A method brings about
some predefined action affecting the associated object. For example, show is a method that can be used
with a hidden form to make it visible.

Common methods of Visual Basic controls:

Method Use

Move Changes an object’s position in response to a code request.

Drag Handles the execution of a drag-and-drop operation by the user.

SetFocus Gives focus to the object specified in the method call.

ZOrder Determines the order in which multiple objects appear onscreen.

EVENTS. Events are what happen in and around your program. For example, when a user clicks a button,
many events occur: The mouse button is pressed; the command button in your program is being clicked;
and then the mouse button is released. Not all controls have the same events, but some events are shared
by many controls. These events occur as a result of some specific user action. These types of events are
user-initiated events and are what you will write code for most often.

Information and Communication Technology Department 2


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
Common events of Visual Basic controls:

Events Occurrence

Change The user modifies text in a combo box or text box.

Click The user clicks the primary mouse button on an object.

DblClick The user double-clicks the primary mouse button on an object.

DragDrop The user drags an object to another location.

DragOver The user drags an object over another control.

GotFocus An object receives focus.

KeyDown The user presses a keyboard key while an object has focus.

KeyPress The user presses and releases a keyboard key while an object has focus.

KeyUp The user releases a keyboard key while an object has focus.

LostFocus An object loses focus.

MouseDown The user presses any mouse button while the mouse pointer is over an object.

MouseMove The user moves the mouse pointer over an object.

MouseUp The user releases any mouse button while the mouse pointer is over an object.

Put simply, Properties describe objects. Methods cause an object to do something. Events are what happen
when an object does something.

Visual Basic Program Components

In Visual Basic, a program is referred to as a project. Every Visual Basic project consists of at least two
separate files – a project file (whose extension is .vbp), and a form file (with extension .frm). Some projects
include multiple form files and other types of files, such as class module (.cls) files, standard module (.bas)
files, resource files (.res) files, and ActiveX control (.ocx) files. Thus, the development of a Visual Basic
project involves keeping track of several different files, and accessing these files individually within the
Visual Basic environment, as needed.

The Visual Basic IDE


The Visual Basic IDE (Integrated Development Environment) is a collection of menus, toolbars, and
windows that make up your programming workbench. Each part of the IDE has features that affect different
aspects of your programming activity. The menu bar lets you handle the overall activity and management of
your programming. The toolbar enables you to access much of the menu bar's functionality through various
toolbar buttons. Forms - the basic building blocks of Visual Basic programs - are presented in a Form
Design window. You use the Toolbox to add controls to the forms of your project. The Project window
displays the projects on which you're working, as well as the different parts of each of those projects. You
browse and set a control, form, and module's properties within the Properties window. Finally, you position
and view a form or forms onscreen within the Form Layout window.

Information and Communication Technology Department 3


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
Menu Bar

Toolbar

Project Window

Toolbox

Properties
Window

Project
Form Layout
Container
Window
Window

Form Design Window

Form Design and Project Container Window

The Form Design Window is where the user interface is actually designed. This is accomplished by selecting
the desired Control Icons from the Toolbox and placing them in the Form Design Window. Each control can
then be moved (place the mouse over the icon and drag) or resized (activate the icon and drag one of the
small surrounding squares), and its properties can be reassigned as required.

The entire form (i.e., the entire Form Design Window) can be moved within the surrounding Project
Container Window (by placing the mouse over the form and dragging), or it can be resized (by activating the
mouse and then dragging one of the small surrounding squares). Both windows can also be closed,
minimized, or resized by clicking on the appropriate icons in their respective Title Bars.

Project Window

The Project Window displays a hierarchical list of the files associated with a given project. These files
represent individual forms and modules. You can display a form or module within the Project Container
Window by double-clicking on the corresponding icon within the Project
Window. Also, you can view the code in each module by clicking on the View
Code button or clicking the View Object button to view the object associated
with each module (for example, a form). You can quickly display the Project
Window or put it in front of other windows by pressing the key combination
CTRL+R or by clicking on the Project Explorer icon on the standard toolbar.

The Form Design Window, which will appear by clicking the View Object
button, is used to design your application’s user interface.

The Code window, on the other hand, to write code that determines the
behavior of your forms and other objects in your application. You can keep a
number of code windows visible at one time, each one displaying the code
related to a form or, more generally, to a module in your application.

Properties Window
Information and Communication Technology Department 4
Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
The Properties window lists all the properties of the object that's currently
selected and gives you the opportunity to modify them. For instance, you
can change the foreground and background colors of the form or the control
that's currently selected. You can list properties in alphabetical order or
group them in categories, and you can find a short description of the
currently selected property near the bottom of this window. When you select
an object, its properties are

The

Form Layout Window


Form
Layout

window shows how a given form


will be displayed or position on the
screen. You can drag a form to the

Toolbox
place on the screen where
you want it to appear during
execution and you can also
compare the relative sizes
and positions of two or more Pointer PictureBox
forms. By right-clicking on (not a control)
this window, you can show its Label TextBox
resolution guides, which
enable you to check how Frame CommandButton
your forms display at screen
resolutions different from the CheckBox OptionButton
current one.
ComboBox ListBox

The Toolbox lets you visually HScrollbar VScrollbar


create the user interface for
your applications. It contains Timer DriveListBox
icons that represent
commonly used controls in DirListBox FileListBox

Code Editor Window Shape Line


Visual Basic. You can select
a control from the Toolbox Image Data
and place it in the current
Form Design window by double-clicking on the control icon, or by clicking once on the control icon, then
clicking on the desired location within the Form Design window and dragging the mouse so that the control
has the desired size.

If you select Code View within the Project Window, or if you double-click on a control icon within the Form
Design Window, the Code Editor Window will open, displaying the Visual Basic code associated with a
particular object. You use the Code Editor Window to write, display, and edit Visual Basic code. You can
open as many code editor windows as you have modules, so you can easily view the code in different forms
or modules, and copy and paste between them. The code editor window contains two list boxes at the top of
Information and Communication Technology Department 5
Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
the window. The leftmost list box is the Object Listbox; it allows you to select the event procedures
associated with a particular object (e.g. command button, form, label, textbox, etc.). The rightmost Listbox is
called the Procedure Listbox; for the current object, it allows you to select the event procedure associated
with a particular type of event (e.g. Click, DragDrop, KeyDown, MouseDown, etc.).

What is a Visual Basic Project?

In Visual Basic, a project is a group of all the files that make up your program. These might include forms,
modules (blocks of code not attached to a form), graphics, and any other type of controls.

The first thing to keep in mind about a project is that as you create your program, each form, module,
graphic, and any other type of control is saved as an individual file.

You can identify the difference between a project and any other file type in Visual Basic using the filename
extension listed below.

File Type Filename Extension

Form frm

Module bas

Automatically generated file for every graphic in your project frx

ActiveX control ocx

Class Module cls

Visual Basic Project vbp

Information and Communication Technology Department 6


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
Creating a New Project

Every time you open Visual Basic, you’ll see the New Project dialog. From this window, you can simply
select the type of project you want to create and click Open.

It is also possible to start a new


project while Visual Basic is already
open, just click File >> New Project
>> select the type of project >> OK.

Saving Visual Basic Applications

When saving Visual Basic applications, you need to be concerned with saving both the forms (.FRM) and
modules (.BAS) and the project file (.VBP). In either case, make sure you are saving in the desired
directory. The current directory is always displayed in the Save window. Use standard Windows techniques
to change the current directory. There are four Save commands available under the File menu in Visual
Basic:

• Save [Form Name] – save the currently selected form or module with the current name. the
selected file is identified in the Project window.
• Save [Form Name] As – like Save File, however you have the option to change the file name.
• Save Project – saves all forms and modules in the current project using their current names and
also saves the project file.
• Save Project As – like Save Project, however you have the option to change file names. When
you choose this option, if you have not saved your forms or modules, you will also be prompted to
save those files.

Opening an Existing Project

1. From the File menu, choose Open Project. The Open Project dialog appears.
2. On the Existing page, navigate to the location where you have saved your existing project. If you
have recently worked on the project, select your project from the list on the Recent page.
3. Select the project and click Open.

Information and Communication Technology Department 7


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
Adding and Removing Files from a Project

ADDING FILES TO A PROJECT

Often, your programs will require more than one form or module. You can add files to your existing project by
right-clicking on the Project window >> choose Add >> select file type you want to add >> Open.

REMOVING FILES FROM A PROJECT

If there’s a file in your project that you don’t want (for example, a form you added accidentally or a module
that contains a form that you no longer needed), you can remove it from you project list. To remove a file
from you project, in the Project window, right-click above the file you want to remove >> from the context
menu, select Remove filename.

Note: When you remove a file from a project, you don’t


actually delete the file from your hard drive. To delete the file
completely, navigate to the location where you have saved the
file and delete it.

Setting Up Your Form

Before drawing any controls on a Form, you should do the following:

Name the Form and Save it

A Form has a name (which is how you refer to it in code) and a filename with .frm extension. When working
with forms in Visual Basic, change the name of the form using the Properties window and save it
immediately using descriptive filenames.

Name property

In Visual Basic, you should always name your Forms and Controls as the first order of business. One
property that every control has and that’s very important to Visual Basic programmers is the Name property.
This is the string of characters that identifies the control in code. This property can't be an empty string, and
you can't have two or more controls on a form with the same name. The special nature of this property is
indirectly confirmed by the fact that it appears as (Name) in the Properties window, where the initial
parenthesis serves to move it to the beginning of the property list.

Because the Name property identifies the control in code, it's a good habit to modify it so that it conveys the
meaning of the control itself. This is as important as selecting meaningful names for your variables.

Microsoft suggests that you always use the same three-letter prefix for all the controls of a given class. The
control classes and their recommended prefixes are shown below.

Control Class Prefix Control Class Prefix

Form frm Frame fra

CommandButton cmd Data dat

TextBox txt HScrollBar hsb

Information and Communication Technology Department 8


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
Label lbl VScrollBar vsb

PictureBox pic DriveListBox drv

OptionButton opt DirListBox dir

CheckBox chk FileListBox fil

ComboBox cbo Line lin

ListBox lst Shape shp

Timer tmr OLE ole

Decide What Kind of Border to Use

By default, your Form will have the familiar blue title bar on top, a "Form" icon, a "Form1" title, minimize,
maximize, and close buttons, (referred to as the Control Box), and be sizable. Any of this can be changed
while designing the Form.

BorderStyle property

• 0 - None No border, title, icon, or control box. The form will not be sizable, or able to be moved by
the user. You are responsible for writing code to close the Form at run time. A common setting for
games.
• 1 - Fixed Single Same as a default form, but the user cannot resize it.
• 2 - Sizable Default
• 3 - Fixed Dialog No minimize or maximize buttons, no Icon, and not sizable by the user. This
setting is used for specialized dialog boxes.
• 4 - Fixed ToolWindow A Tool Window has a slimmer title bar, and no minimize or maximize
buttons. Use this setting as a utility form, such as a toolbox.
• 4 - Sizable ToolWindow Same as above but able to be resized by the user.

MinButton, MaxButton, and ControlBox properties

These three properties can be set to True or False. Setting ControlBox to False will remove all three buttons.
Setting MinButton or MaxButton to False will not totally remove the button, but rather just gray it out so it
cannot be used. Setting both MinButton and MaxButton to False will remove both buttons.

WindowState property

Set this property at design time to indicate how the Form will be displayed initially.

• 0 - Normal The Form will display according to the size and location you decided at design time. In
most cases, you'll use this setting which is also the default.
• 1 - Minimized The Form will start up minimized as an icon in the Windows Taskbar.
• 2 - Maximized The Form will run full screen, but this may not be a good idea if you're eventually
going to run your program on different machines, due to the different screen sizes. You might think
your controls are nicely placed until you run the Form on a different computer with a larger screen
size and find a lot of empty space or on a smaller screen size and the whole Form doesn't seem to
be there.

StartUpPosition property

If your Form is not maximized, you'll need to place it in an appropriate place on the screen. You can do this
with the Form Layout Window or set the StartUpPosition property.
Information and Communication Technology Department 9
Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
• 0 - Manual You'll set the Left and Top properties of the Form in the Form's Load event.
• 1 - CenterOwner The form will be centered on the form which owns it.
• 2 - CenterScreen The Form will run centered on the screen. A most pleasing effect in my opinion.
• 3 - Windows Default This is the default setting. You're putting the decision into the hands of
Windows, which can be unpredictable.

Moveable property

By default, the Moveable property is set to True, meaning users will be able to move your Forms by dragging
on the title bar. Set this property to False to create a non-moveable Form. This won't affect whether or not
the Form can resized.

Caption property

This is the title of your Form. It will appear on the left side of the title bar next to the Icon. You can set this
property dynamically, (which simply means at run time by writing code), if your Form has multiple purposes
and needs different titles at different times.

Icon property

Set this property to an icon picture file if you don't like the "Form" icon. Actually, using the default form icon is
somewhat non-professional. The icon can be changed at run time by setting the property with the
LoadPicture function or setting it to a picture which is already a property of another Form or Control with a
Picture property. The standard Windows icon is also available by going to a Form's Properties Window,
highlighting the (Icon) text and pressing the delete key.

Picture property

Set this property to any valid picture file to set a background for your Form. The picture file should be of the
correct size, you cannot stretch, shrink, center, or tile it without some help from Bit Block Transfer.

Intrinsic Controls

In Microsoft Visual Basic jargon, intrinsic controls (or built-in controls) are those controls visible in the
Toolbox window when you launch Visual Basic. This important group includes controls, such as Label,
Textbox, CommandButton controls, etc. that are used in nearly every application.

TextBox

TextBox controls offer a natural way for users to enter a value in your program. For this reason, they tend to
be the most frequently used controls in the majority of Windows applications. TextBox can also be used to
display text.

Label

Most people use Label controls to provide a descriptive caption and possibly an associated hot key for other
controls, such as TextBox, ListBox, and ComboBox, that don't expose the Caption property. In most cases,
you just place a Label control where you need it, set its Caption property to a suitable string (embedding an
ampersand character in front of the hot key you want to assign), and you're done. Caption is the default
property for Label controls.

Frame

Information and Communication Technology Department 10


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
Frame controls are similar to Label controls in that they can serve as captions for those controls that don't
have their own. Moreover, Frame controls can also (and often do) behave as containers and host other
controls. In most cases, you only need to drop a Frame control on a form and set its Caption property. If you
want to create a borderless frame, you can set its BorderStyle property to 0-None.

CommandButton

Using CommandButton controls is trivial. In most cases, you just draw the control on the form's surface, set
its Caption property to a suitable string (adding an & character to associate a hot key with the control if you
so choose), and you're finished, at least with user-interface issues. To make the button functional, you write
code in its Click event procedure.

CheckBox

CheckBox controls are useful when you want to offer your users a yes or no, true or false choice. Anytime
you click on this control, it toggles between the yes state and the no state. This control can also be grayed
when the state of the CheckBox is unavailable, but you must manage that state through code.

OptionButton

OptionButton controls are also known as radio buttons because of their shape. You always use OptionButton
controls in a group of two or more because their purpose is to offer a number of mutually exclusive choices.
Anytime you click on a button in the group, it switches to a selected state and all the other controls in the
group become unselected.

ListBox

Once you have dropped a ListBox control on a form's surface, you might need to assign a few properties.
For example, you set the Sorted attribute to True to create ListBox controls that automatically sort their items
in alphabetical order. ListBox are controls that enable users to select from a list of available items.

ComboBox

ComboBox controls are similar to ListBox controls. It allows users to select from a list of items or add a new
value.

PictureBox

PictureBox controls are among the most powerful and complex items in the Visual Basic Toolbox window. It
support all the properties related to graphic output. PictureBox also displays graphics (images) on a form
and can serve as a container.

Image

Image controls are far less complex than PictureBox controls. They don't support graphical methods, and
can’t work as containers. Nevertheless, you should always strive to use Image controls instead of
PictureBox controls because they load faster and consume less memory and system resources. Image
controls can also load bitmaps, JPEG and GIF images.

Scrollbar

The HScrollBar and the VScrollBar controls are perfectly identical, apart from their different orientation. You'll
use the scroll bar controls for such things as allowing the user to set a value from a range, or to measure
progress.

DriveListBox, DirListBox, and FileListBox

Information and Communication Technology Department 11


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
The DriveListBox control is a combobox-like control that's automatically filled with your drive's letters and
volume labels. The DirListBox is a special list box that displays a directory. The FileListBox control is a
special-purpose ListBox control that displays all the files in a given directory, optionally filtering them based
on their names, extensions, and attributes.

These controls often work together on the same form; when the user selects a drive in a DriveListBox, the
DirListBox control is updated to show the directory on that drive. When the user selects a path in the
DirListBox control, the FileListBox control is filled with the list of files in that directory. These actions don't
happen automatically, however—you must write code to get the job done.

Timer

Timer control is invisible at run time, and its purpose is to send a periodic pulse to the current application.
You can trap this pulse by writing code in the Timer's Timer event procedure and take advantage of it to
execute a task in the background or to monitor a user's actions. This control exposes only two meaningful
properties: Interval and Enabled. Interval stands for the number of milliseconds between subsequent pulses
(Timer events), while Enabled lets you activate or deactivate events. When you place the Timer control on a
form, its Interval is 0, which means no events.

Line

The Line control is a decorative control whose only purpose is let you draw one or more straight lines at
design time. This control exposes a few properties whose meaning should sound familiar to you by now:
BorderColor (the color of the line), BorderStyle (the same as a form's DrawStyle property), BorderWidth (the
same as a form's DrawWidth property), and DrawMode.

Shape

In a sense, the Shape control is an extension of the Line control. It can display six basic shapes: Rectangle,
Square, Oval, Circle, Rounded Rectangle, and Rounded Square. It supports all the Line control's properties
and a few more: BorderStyle (0-Transparent, 1-Solid), FillColor, and FillStyle (the same as a form's
properties with the same names).

Data

The Data control provides a link to database files.

Adding and Removing Controls

You can add controls to a form in two ways: (1) by double-clicking and (2) by drawing. Whenever you
double-click an icon on the toolbox, the associated control appears on you form. To position the control,
simply drag it to your desired location.

The second method is by drawing, to do this, click the control’s toolbox icon >> Move the mouse pointer
over your form, click (and hold) the mouse button where you want the control to go >> Drag the mouse down
slightly and to the left. As you move the mouse, a box starts to appear >> When the box is in its proper size,
let go of the mouse. The control you selected now appears on the form.

To remove a control from a form:


1. Select the control you want to delete by clicking it. The control you select will appear with a box at
each corner and side.
2. Press the DELETE key on the keyboard.

Information and Communication Technology Department 12


Palompon Institute of Technology
INTRODUCING VISUAL BASIC
1
Running a Visual Basic Project

To execute a Visual Basic project, simply click on the Start/Play button in the Toolbar, or select Start from the
Run menu. The execution can be suspended by clicking on the Break button, or by selecting Break from the
Run menu. The execution of a paused project can then be resumed by clicking on the Run button, or by
selecting Continue from the Run menu. To end the execution, simply click on the End button, or select End
from the Run menu.

Controlling How Your Program Starts

When you first start a programming project, Visual Basic assumes that the first form created is the one that
will be displayed as soon as the program starts. Although this will be the case for many programs, for others
you may want to start with one of the forms you create later in the development process.

If the first form is not the one you want to use to start your program, Visual Basic lets you choose which of
your form is shown initially by the program. This selection is made in the Project Properties dialog box, as
shown below. You can access this dialog box by selecting Project >> Project Properties.

The Startup Object list


lets you choose which
form is loaded when
your program starts.

Information and Communication Technology Department 13


Palompon Institute of Technology

Potrebbero piacerti anche