visual basic notes1
Post on 03-Jun-2018
238 Views
Preview:
TRANSCRIPT
-
8/12/2019 Visual Basic Notes1
1/36
Visual Basic
Mrs. Poornima Shankar. Page 1
Introduction to Visual Basic
Visual Basic is a programming language and development environment created byMicrosoft.
Visual Basic provides a graphical user interface GUI that allows the developer dragand drop objects into the program as well as manually write program code.
Visual Basic, also referred to as "VB," is designed to make software developmenteasy and efficient
Visual Basic 6.0
1. Visual Basic is a programming language and integrated development environment.
2. It derives from the much older BASIC programming language, and so is considereduseful and easy programming language for the beginner to learn.
3. Visual Basic 6.0 was the final edition of Visual Basic.
What is Visual Basic?
VISUAL BASICis a high level programming language which evolved from the earlier DOSversion called BASIC. BASICmeans Beginners' All-purpose Symbolic Instruction Code. Itis a very easy programming language to learn. The code look a lot like English Language.Different software companies produced different versions of BASIC, such as MicrosoftQBASIC, QUICKBASIC, GWBASIC ,IBM BASICA and so on. However, people prefer touse Microsoft Visual Basic today, as it is a well developed programming language andsupporting resources are available everywhere. Now, there are many versions of VB exist inthe market, the most popular one and still widely used by many VB programmers is noneother than Visual Basic 6. We also have VB.net, VB2005, VB2008 and the latest VB2010.Both Vb2008 and VB2010 are fully object oriented programming (OOP) language.
VISUAL BASIC is a VISUAL and events driven Programming Language. These are themain divergence from the old BASIC. In BASIC, programming is done in a text-onlyenvironment and the program is executed sequentially. In VB, programming is done in agraphical environment. In the old BASIC, you have to write program code for each graphicalobject you wish to display it on screen, including its position and its color. However, In VB ,you just need to drag and drop any graphical object anywhere on the form, and you can
change its color any time using the properties windows.
On the other hand, because the user may click on a certain object randomly, so each objecthas to be programmed independently to be able to response to those actions (events).Therefore, a VB Program is made up of many subprograms, each has its own program code,and each can be executed independently and at the same time each can be linked together inone way or another.
Feature Of visual basic 6.0
1. Learning Consists of all necessary tools required to build main stream WindowsApplications
-
8/12/2019 Visual Basic Notes1
2/36
Visual Basic
Mrs. Poornima Shankar. Page 2
2. Professional Includes advanced features such as tools to develop ActiveX and Internetcontrols.3. Enterprise In addition to all Professional features, it also includes tools such as Visual
Features of visual basic
GUI Interface
Modularization
Object Oriented
Debugging
Macros IDE
Data access feature
Guo Interface: - VB is a Graphical User Interface language. This means that a VB programwill always show something on the screen that the user can interact with to get a job done.
Modularization: - It is considered good programming practice to modularize your programs.Small modules where it is clearly indicated what comes into the module and what goes outmakes a program easy to understand.
Object Oriented: - Object Oriented Programming is a concept where the programmer thinksof the program in "objects" that interact with each other. Visual Basic forces this good
programming practice.
Debugging: - Visual Basic offers two different options for code debugging:- DebuggingManaged Code Runtime Debugger The Debugging Managed Code individually debugs C andC++ applications and Visual Basic Windows applications. The Runtime Debugger helps tofind and fix bugs in programs at runtime.
Data Access Feature: - By using data access features, we can create databases, scalableserver-side components for most databases, including Microsoft SQL Server and otherenterprise-level database.
Macros IDE: - The Macros integrated development environment is similar in design andfunction to the Visual Studio IDE. The Macros IDE includes a code editor, tool windows, the
properties windows and editors.
Parts of a Visual Basic project
Three major components in a Visual Basic project: the project itself, the form, and the
controls. Projectis the word used to encompass everything in a Visual Basic project. Other
words used to describe a project are applicationor program. The Formis the window
where you create the interface between the user and the computer. Controlsare graphical
-
8/12/2019 Visual Basic Notes1
3/36
Visual Basic
Mrs. Poornima Shankar. Page 3
features or tools that are placed on forms to allow user interaction (text boxes, labels, scroll
bars, command buttons). Recall the form itself is a control. Controls are also referred to as
objects. Pictorially, a project is:
..DIAGRAM
So, a project consists of a form containing several controls. In looking around your
computers file directory, you may find some files associated with a Visual Basic project.
Two primary files are used to save a Visual Basic project. The project file will have an
extension of vbp(in addition, there is sometimes a file with a vbw extension). The form file
has an extension of frm(in addition, there is sometimes a form file with a frx extension).
An important concept concerning a Visual Basic project is that of a property. Every
characteristic of a control (including the form itself) is specified by a property. Example
properties include names, captions, sizes, colors, position on the form, and contents.
Event Driven Programming
Visual Basic programs are built around events. Events are various things that can happen in aprogram. this will become clearer when studied in contrast to procedural programming. Inprocedural languages, an application is written is executed by checking for the program
logically through the program statements, one after another. For a temporary phase, thecontrol may be transferred to some other point in a program. While in an event drivenapplication, the program statements are executed only when a particular event calls a specific
part of the code that is assigned to the event.
Let us consider a TextBox control and a few of its associated events to understand theconcept of event driven programming. The TextBox control supports various events such asChange, Click, MouseMove and many more that will be listed in the Properties dropdown listin the code window for the TextBox control. We will look into a few of them as given below.
The code entered in the Change event fires when there is a change in thecontents of the TextBox The Click event fires when the TextBox control is clicked. The MouseMove event fires when the mouse is moved over the TextBox
As explained above, several events are associated with different controls and forms, some ofthe events being common to most of them and few being specific to each control.
Data types in Visual Basic
-
8/12/2019 Visual Basic Notes1
4/36
Visual Basic
Mrs. Poornima Shankar. Page 4
By default Visual Basic variables are of variant data types. The variant data type can storenumeric, date/time or string data.
When a variable is declared, a data type is supplied for it that determines the kind of data theycan store.
The fundamental data types in Visual Basic including variant are integer, long, single,double, string, currency, byte and boolean.
Each data type has limits to the kind of information and the minimum and maximum values itcan hold.
1. Numeric
Byte Store integer values in the range of 0 255
Integer Store integer values in the range of (-32,768) - (+ 32,767)
LongStore integer values in the range of (- 2,147,483,468) - (+
2,147,483,468)
Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)
Double Store large floating value which exceeding the single data type value
Currency store monetary values. It supports 4 digits to the right of decimalpoint and 15 digits to the left
2. String
Use to store alphanumeric values. A variable length string can store approximately 4 billioncharacters
3. Date
Use to store date and time values. A variable declared as date type can store both date andtime values and it can store date values 01/01/0100 up to 12/31/9999
4. Boolean
Boolean data types hold either a true or false value. These are not stored as numeric valuesand cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and anynon-zero value is considered as true.
5. Variant
-
8/12/2019 Visual Basic Notes1
5/36
Visual Basic
Mrs. Poornima Shankar. Page 5
Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declarea variable without any data type by default the data type is assigned as default.
Operators in Visual Basic
Arithmetical Operators
Operators Description ExampleResult
+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
* Multiply 5*4 20
^Exponent (power
of)3^3 27
Mod
Remainder of
division 20 Mod 6 2
& String concatenation"George"&"
"&"Bush""George Bush"
Relational Operators
Operators Description Example Result
> Greater than 10>8 True
< Less than 10=Greater than or equal
to20>=10 True
-
8/12/2019 Visual Basic Notes1
6/36
Visual Basic
Mrs. Poornima Shankar. Page 6
-
8/12/2019 Visual Basic Notes1
7/36
Visual Basic
Mrs. Poornima Shankar. Page 7
Dim MyName As String
Dim StudentDOB As Date
Dim Amount5, Amount6, Amount7
In the last example the type assigned to each variable will be: Variant. It is the default type
when none is specified.
There can be multiple explicit declarations in a statement:
Dim EmpName As String, SalaryMonth As Currency, SalaryYear As Currency
In this final example, what are the types assigned to the three variables:Dim Amount1, Amount2, Amount3 As Single
All Single-precision floating point, you say. Wrong!Only Amount3 is Single. Amount1 andAmount2 are considered Variant because VB specifies that each variable in a statement must
be explicitly declared. Thus Amount1 and Amount2 take the default data type. This is
different from what most other languages do.
Constants
A constant is a value that does not change during the execution of a procedure. The constantis defined with:
Const ValuePi = 3.1416
The Scope of variables
The term Scoperefers to whether the variable is available outside the procedure in which it
appears. The scope is procedure-levelor module-level.
A variable declared with Dim at the beginning of a procedure is only available in that
procedure. When the procedure ends, the variable disappears. Consider the following
example:
Option Explicit
Dim Total2 As Integer
Private Sub Command1_Click ()
Dim Total1 As Integer
Static Total3 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Private Sub Command2_Click ()
-
8/12/2019 Visual Basic Notes1
8/36
Visual Basic
Mrs. Poornima Shankar. Page 8
Dim Total1 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Every time Button1 is clicked, Total1 is declared as a new variable during the execution of
that clicked event. It is a procedure-levelvariable. It will always stay at 1. The same for the
Button2 event: Total1 is a new variable in that procedure. When the procedure ends, Total1
disappears.
Total2 is declared in the Declarations section. It is a module-levelvariable, meaning it is
available to every control in this Form. When Button1 is clicked, it increments by 1 and it
retains that value. When Button2 is clicked, Total2 is incremented from its previous value,
even if it came from the Button1 event.
Total3 shows another way of retaining the value of a local variable. By declaring it with
Staticinstead of Dim, the variable acts like a module-level variable, although it is declared in
a procedure.
Another scope indicator that you will see when you study examples of code is Privateand
Public. This determines whether a procedure is available only in this Form (module) or if it is
available to any module in the application. For now, we will work only with Private
procedures
Interface Components:
Object
Object Is An Real Time Entity Which Is Used To Access The Members (Properties,Methhods Etc)
It Comes With The Name.(Object Name). By Using This Object , The Period Or Dot Operator Is Used. It Is Used To Generate Application.
Ex :Textbox --- Contains Name As Text1
Events
Events are actions the user can perfom, which objects can be programmed to respond to, suchas click, double-click, keypress etc. An event is an action recognized by an object. Clicking amouse or pressing a key are examples of events.
Some events include:
-
8/12/2019 Visual Basic Notes1
9/36
Visual Basic
Mrs. Poornima Shankar. Page 9
Activate DragOver Load
Change GotFocus LostFocus
Click KeyDown MouseDown
DblClick KeyPress MouseMove
DragDrop KeyUp MouseUp
Each object has its own set of events that it recognizes. The events listed do not apply to allobjects. For example, a form can recognize either a Click or DblClick event while a buttononly recognizes a Click event.
Method
A method is an action that can be performed on objects. Method is something that object does.
Ex:Motor Vehicle Has Properties Like Colour, Model, And Speed.Starting And Stopping That The Vehicle Does.Vehicle Is A Visual Basic Object, Start And Stop Are Two Methods.
It is used to specify how the action is to take place. The Action Taken When The Event Occurs . When The Event Occurs , Respective Method Invoked.
Private Sub Command1_Click()Text1.ToolTipText = "TEXTBOX"End Sub
Properties
All the controls in the ToolBox except the Pointer are objects in Visual Basic. These objectshave associated properties, methods and events.
Real world objects are loaded with properties. For example, a flower is loaded certain color,shape and fragrance. Similarly programming objects are loaded with properties. A property isa named attribute of a programming object. Properties define the characteristics of an objectsuch as Size, Color etc. or sometimes the way in which it behaves. For example, a TextBoxaccepts properties such as Enabled, Font, MultiLine, Text, Visible, Width, etc.
Enables property allows the TextBox to be enabled or disabled at run timedepending on the condition set to True or False. Font property sets a particular font in the TextBox.
-
8/12/2019 Visual Basic Notes1
10/36
Visual Basic
Mrs. Poornima Shankar. Page 10
MultiLine property allows the TextBox to accept and display multiple lines atrun time.
Text property of the TextBox control sets a particular text in the control. Visible property is used to hide the object at run time. Width property sets the TextBox to the desired width at design time.
The properties that are discussed above are design-time properties that can be set at thedesign tme by selecting the Properties Window. But certain properties cannot be set at desgntime. For example, the CurrentX and CurrentY properties of a Form cannot be set at thedesign time.
Resolution
It is represented in the form of pixels.Ex: contrast
MDI(Multiple Document Interface)
The Multiple Document Interface (MDI) was designed to simplify the exchange ofinformation among documents, all under the same roof.
With the main application, you can maintain multiple open windows, but not multiplecopies of the application.
Data exchange is easier when you can view and compare many documentssimultaneously.
You almost certainly use Windows applications that can open multiple documents atthe same time and allow the user to switch among them with a mouse-click. MultipleWord is a typical example, although most people use it in single document mode.
Each document is displayed in its own window, and all document windows have thesame behavior.
The main Form, or MDI Form, isn't duplicated, but it acts as a container for all thewindows, and it is called the parent window.
The windows in which the individual documents are displayed are called Childwindows.
An MDI application must have at least two Form, the parent Form and one or morechild Forms.
Each of these Forms has certain properties. There can be many child forms containedwithin the parent Form, but there can be only one parent Form.
COLOR BASICS:It is used to display the colors on the controls.VBCOLOR CONSTANTS:
vbred vbblue vbyellowQUICK BASIC COLOR :
-
8/12/2019 Visual Basic Notes1
11/36
Visual Basic
Mrs. Poornima Shankar. Page 11
qbcolor(1)qbcolor(2)qbcolor(3)
IT RANGES FROM 1 TO 15
Private Sub Command1_Click()Text1.BackColor = QBColor(8)End Sub
TEXT BUTTONS:
When the style of the button is set to standard, then it is text button. Then the caption property of the button can contain text. When the style of the button is set to graphical , Then picture can be inserted or placed by using a property called "picture".
FONT:
This property is used to set the font name, style , size of the text to the control.
Eg: TEXTBOXCOMMAND BUTTON
Private Sub Command1_Click()Text1.FontSize = 20
Text1.FontBold = TrueText1.FontItalic = TrueText1.FontUnderline = TrueText1.Text = "VISUAL BASIC"End Sub
FORMS:
Form is used to customize design the interface of user application. On the form , controls can be added. Graphics and pictures can be added. Form is an object. It has got properties.
The Multiple Document Interface (MDI) in Visual Basic 6
The Multiple Document Interface (MDI) was designed to simplify the exchange ofinformation among documents, all under the same roof. With the main application, you canmaintain multiple open windows, but not multiple copies of the application. Data exchange iseasier when you can view and compare many documents simultaneously.
You almost certainly use Windows applications that can open multiple documents at the
same time and allow the user to switch among them with a mouse-click. Multiple Word is atypical example, although most people use it in single document mode. Each document is
-
8/12/2019 Visual Basic Notes1
12/36
Visual Basic
Mrs. Poornima Shankar. Page 12
displayed in its own window, and all document windows have the same behavior. The mainForm, or MDI Form, isn't duplicated, but it acts as a container for all the windows, and it iscalled the parent window. The windows in which the individual documents are displayed arecalled Child windows.
An MDI application must have at least two Form, the parent Form and one or more childForms. Each of these Forms has certain properties. There can be many child forms containedwithin the parent Form, but there can be only one parent Form.
The parent Form may not contain any controls. While the parent Form is open in designmode, the icons on the ToolBox are not displayed, but you can't place any controls on theForm. The parent Form can, and usually has its own menu.
To create an MDI application, follow these steps:
1. Start a new project and then choose Project >>> Add MDI Form to add theparent Form.2. Set the Form's caption to MDI Window3. Choose Project >>> Add Form to add a SDI Form.4. Make this Form as child of MDI Form by setting the MDI Child property ofthe SDI Form to True. Set the caption property to MDI Child window.
Visual Basic automatically associates this new Form with the parent Form. This child Formcan't exist outside the parent Form; in the words, it can only be opened within the parentForm.
Parent and Child Menus
MDI Form cannot contain objects other than child Forms, but MDI Forms can have their ownmenus. However, because most of the operations of the application have meaning only ifthere is at least one child Form open, there's a peculiarity about the MDI Forms. The MDIForm usually has a menu with two commands to load a new child Form and to quit theapplication. The child Form can have any number of commands in its menu, according to theapplication. When the child Form is loaded, the child Form's menu replaces the original menuon the MDI Form
Following example illustrates the above explanation.
-
8/12/2019 Visual Basic Notes1
13/36
Visual Basic
Mrs. Poornima Shankar. Page 13
* Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp
* Design a menu that has the following structure.
MDIMenu Menu caption
MDIOpen opens a new child Form MDIExit terminates the application
* Then design the following menu for the child Form
ChildMenu Menu caption
Child Open opens a new child Form Child Save saves the document in the active child Form Child Close Closes the active child Form
At design time double click on MDI Open and add the following code in the click event ofthe open menu.
Form1.Show
And so double click on MDI Exit and add the following code in the click event
End
Double click on Child Close and enter the following code in the click event
Unload Me
Before run the application in the project properties set MDI Form as the start-up Form. Saveand run the application. Following output will be displayed.
And as soon as you click MDI Open you can notice that the main menu of the MDI Form isreplaced with the Menu of the Child Form. The reason for this behavior should be obvious.The operation available through the MDI Form are quite different from the operations of thechild window. Moreover, each child Form shouldn't have it's own menu.
DIALOG BOX:
-
8/12/2019 Visual Basic Notes1
14/36
Visual Basic
Mrs. Poornima Shankar. Page 14
Dialog box is used to provide the user information and accepts the information from the user.
Inputbox MessageboxInputbox:
It is used to accept the values It provides two buttons. Ok and cancel button.
Messgebox (msgbox) :
Used to display the messages. It provides only one button. Ok button.
Msgbox and InputBox are similar to functions which are used to display the information to
the user and possibly to get a response as well.Private Sub Command1_Click()Dim a As Integera = InputBox("enter the value")MsgBox (a)End Sub
ADDING TWO VALUES :Private Sub Command1_Click()Dim a, b As IntegerDim c As Integer
a = InputBox("enter the value")b = InputBox("enter the second value")c = a + bPrint "The value is " & cEnd Sub
MENUS:
Windows applications use a menu to give users full control. Windows applications provide groups of related commands in Menus. These
commands depend on the application, but some-such as Open and save are frequentlyfound in applications.
On the other hand, menus behave differently from other controls.TOOLS -- MENU EDITOR
NAME OBJECT NAMECOLOR mnucolor
RED mnuredBLUE mnublue
SIZE mnusizeLARGE mnulargeSMALL mnusmall
Private Sub mnublue_Click()Form1.BackColor = vbBlue
-
8/12/2019 Visual Basic Notes1
15/36
Visual Basic
Mrs. Poornima Shankar. Page 15
mnured.Enabled = Truemnublue.Enabled = blueEnd Sub
Private Sub mnularge_Click()
Form1.WindowState = 2mnularge.Enabled = Falsemnusmall.Enabled = TrueEnd SubPrivate Sub mnured_Click()Form1.BackColor = vbRedmnured.Enabled = Falsemnublue.Enabled = TrueEnd Sub
Private Sub mnusmall_Click()
Form1.WindowState = 0mnusmall.Enabled = Falsemnularge.Enabled = TrueEnd Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y AsSingle)If Button = 2 ThenPopupMenu mnucolorEnd IfEnd Sub
Scroll bar
Scrolls through a range of values when you click the scroll arrows or when you dragthe scroll box.
You can move through a page (a preset interval) of values by clicking the regionbetween the scroll box and either scroll arrow.
Typically, a user can also type a text value directly in the associated cell or text box. Use a scroll bar for setting or adjusting a large range of values, or for cases when
precision is not important.
For example, use a scroll bar for a range of percentages that are estimates, or foradjusting color selection in a graduated way.
Private Sub hscroll1_Change ()Dim a, b, c as IntegerA = hscroll1.ValueB = hscroll1.ValueC = hscroll1.Value
-
8/12/2019 Visual Basic Notes1
16/36
Visual Basic
Mrs. Poornima Shankar. Page 16
Form1.backcolor = RGB (6 * a, 4 * b, 2 * c)Label1.forecolor = RGB (6 * a, 4 * b, 2 * c)End Sub
Private Sub VScroll1_Change()
Form1.Font = VScroll1.ValueLabel1.FontSize = VScroll1.Value
Text1.Text = VScroll1.ValueEnd Sub
Scroll bar Scrolls through a range of values when you click the scroll arrows or when youdrag the scroll box. You can move through a page (a preset interval) of values by clicking theregion between the scroll box and either scroll arrow. Typically, a user can also type a textvalue directly in the associated cell or text box. Use a scroll bar for setting or adjusting alarge range of values, or for cases when precision is not important. For example, use a scroll
bar for a range of percentages that are estimates, or for adjusting color selection in a
graduated way.
Scroll bar (Form control)Scroll bar (ActiveX control)
Spin button Makes it easier to increase or decrease a value, such as a number increment,time, or date. To increase the value, click the up arrow; to decrease the value, click the downarrow. A user can also type a text value directly in the associated cell or text box. Use a spin
button, for example, to make it easier to enter a month, day, year number, or to increase avolume level.
Spin button (Form control) Spin button (ActiveX control)
-
8/12/2019 Visual Basic Notes1
17/36
Visual Basic
Mrs. Poornima Shankar. Page 17
Spin button
Spin button makes it easier to increase or decrease a value, such as a numberincrement, time, or date.
To increase the value, click the up arrow; to decrease the value, click the down arrow.A user can also type a text value directly in the associated cell or text box.
OptionButton Controls
OptionButton controls are also known as radio buttons because of their shape. 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 theother controls in the group become unselected.
A group of OptionButton controls is often hosted in a Frame control. This isnecessary when there are other groups of OptionButton controls on the form.
As far as Visual Basic is concerned, all the OptionButton controls on a form's surfacebelong to the same group of mutually exclusive selections, even if the controls are
placed at the opposite corners of the window.
The only way to tell Visual Basic which controls belong to which group is bygathering them inside a Frame control.
Example
FRAME, OPTION BUTTONS 4 , 3 TEXTBOXPrivate Sub Form_Load()Text1 = " "Text2 = " "Text3 = " "
End Sub
Private Sub Option1_Click()Text3.Text = Val(Text1) + Val(Text2)End Sub
Private Sub Option2_Click()Text3.Text = Val(Text1) - Val(Text2)End Sub
-
8/12/2019 Visual Basic Notes1
18/36
Visual Basic
Mrs. Poornima Shankar. Page 18
Private Sub Option3_Click()Text3.Text = Val(Text1) * Val(Text2)End Sub
Private Sub Option4_Click()Text3.Text = Val(Text1) / Val(Text2)End Sub
The PictureBox Control
PictureBox controls are among the most powerful and complex items in the VisualBasic Toolbox window.
In a sense, these controls are more similar to forms than to other controls. Forexample, PictureBox controls support all the properties related to graphic output,
including AutoRedraw, FontTransparent, CurrentX, CurrentY properties.
PictureBox controls also support all graphic methods, such as Point, Line, and Circleand conversion methods, such as ScaleX, ScaleY, TextWidth, and TextHeight.
Combo Box
A ComboBox combines the features of a TextBox and a ListBox. This enables the user to
select either by typing text into the ComboBox or by selecting an item from the list. There are
three types of ComboBox styles that are represented as shown below.
Dropdown Combo (style 0) Simple Combo (style 1) Dropdown List (style 2)
The Simple Combo box displays an edit area with an attached list box always visible
immediately below the edit area. A simple combo box displays the contents of its list all the
time. The user can select an item from the list or type an item in the edit box portion of the
combo box. A scroll bar is displayed beside the list if there are too many items to be
displayed in the list box area.
-
8/12/2019 Visual Basic Notes1
19/36
Visual Basic
Mrs. Poornima Shankar. Page 19
The Dropdown Combo box first appears as only an edit area with a down arrow button at the
right. The list portion stays hidden until the user clicks the down-arrow button to drop down
the list portion. The user can either select a value from the list or type a value in the edit area.
The Dropdown list combo box turns the combo box into a Dropdown list box. At run time ,
the control looks like the Dropdown combo box. The user could click the down arrow to view
the list. The difference between Dropdown combo & Dropdown list combo is that the edit
area in the Dropdown list combo is disabled. The user can only select an item and cannot type
anything in the edit area. Anyway this area displays the selected item
IN THE FIRST COMBO BOXLIST PROPERTY
ChamundiShatabdiTippu
IN SECOND COMBO BOXLIST PROPERTYSunday,Monday, Tuesday,Wednesday, Thursday,Friday, Saturday
Private Sub Command1_Click()If (Combo1.Text = "Chamundi" And Combo2.Text = "Friday") ThenMsgBox " Train ply on friday"ElseIf (Combo1.Text = "Shatabdi" And Combo2.Text = "Saturday") ThenMsgBox " Train ply on saturday"ElseIf (Combo1.Text = "Tippu" And Combo2.Text = "Tuesday") ThenMsgBox " Train ply on tuesday"ElseMsgBox " train does not ply"End IfEnd Sub
CHECKBOX :It is used to make multiple selection and deselection.
Dim amount As IntegerPrivate Sub Check1_Click()If (Check1.Value = 1) Thenamount = amount + 20Text1.Text = amountElseamount = amount - 20Text1.Text = amount
End If
-
8/12/2019 Visual Basic Notes1
20/36
Visual Basic
Mrs. Poornima Shankar. Page 20
End Sub
Private Sub Check2_Click()If (Check2.Value = 1) Thenamount = amount + 300
Text1.Text = amountElseamount = amount - 300Text1.Text = amountEnd IfEnd Sub
Private Sub Check3_Click()If (Check3.Value = 1) Thenamount = amount + 800Text1.Text = amount
Elseamount = amount - 800Text1.Text = amountEnd IfEnd Sub
Private Sub Check4_Click()If (Check4.Value = 1) Thenamount = amount + 3000Text1.Text = amountElseamount = amount - 3000Text1.Text = amountEnd IfEnd Sub
Private Sub Form_Load()
End Sub
Pen & Brush
A pen is an instance of the Penclass, and is used to draw lines and outlined shapes.
A pen is used to draw lines, curves, and to outline shapes.
A brush is an instance of any class that derives from the MustInherit (abstract) Brushclass,and can be used to fill shapes or paint text.
Brushes are objects that are used with a Graphicsobject to create solid shapes and to rendertext.
' Creates a pen that draws in red.
-
8/12/2019 Visual Basic Notes1
21/36
Visual Basic
Mrs. Poornima Shankar. Page 21
Dim myPen as New Pen(Color.Red)
' Creates a brush that fills in solid blue.
Dim myBrush as New SolidBrush(Color.Blue)
CONTROL BUTTONS:
It is a control array Click the right mouse button select properties Select copy And click the right mouse button Select paste
LISTBOX:
It is used to list the items. It contains a property called list Additem : it is used to add items to list box Removeitem : it is used to remove item from list box and combo box.
private Sub Command1_Click()List1.AddItem ("abc")List1.AddItem ("xyz")List1.AddItem ("mno")List1.AddItem ("xxx")List1.AddItem ("ppp")End Sub
OR
Private Sub Command1_Click()List2.AddItem "abc"List2.AddItem "xyz"List2.AddItem "mno"End Sub
ADDING ITEMS AT THE RUNTIME TO LIST BOX:
LISTBOX , TEXT BOXCOMMAND BUTTON
Private Sub Command2_Click()List2.AddItem Text1.TextEnd Sub
SLIDER CONTROL:It is a window containing a slider and optional tick marks. It is like a scroll bar withoutnumbers or tick marks.
Slide can be used to
-
8/12/2019 Visual Basic Notes1
22/36
Visual Basic
Mrs. Poornima Shankar. Page 22
Select a particular value Select a range of numbers to be passed into an array. Resize a form or other graphic object.Private Sub Form_Load()
Slider1.Max = 800Slider1.Min = 0
End Sub
Private Sub Slider1_Click()Text1.Text = ""Text1.BackColor = RGB(0, 0, Slider1.Value)End Sub
CURSOR:
It is a set of pointer that point to the data.
Picture animation program:Project ---components--- controls tab--- Microsoft windows common control 6.0
Image list:Click the right mouse buttonSelect propertiesSelect images tabInsert picture one by one
Select picture or image control , timer , command button
Timer:It is used to run the loop infinitelyIt is used to set the delay.Design time property setting:Timer-----interval ---500 ( half second)Enabled --- false
Dim x as integer
Private sub command1_click()Timer1.enabled = trueCommand1.visible = false
End sub
Private sub timer1_timer()X = x + 1If x = 1 thenImage1.picture = imagelist1.listimages(1).picture
Elseif x = 2 thenImage1.picture = imagelist1.listimages(2).picture
-
8/12/2019 Visual Basic Notes1
23/36
Visual Basic
Mrs. Poornima Shankar. Page 23
Elseif x = 3 thenImage1.picture = imagelist1.listimages(3).pictureElseif x = 4 thenX = 0End if
End sub
CommandButton and OptionButton Controls
When compared to TextBox controls, these controls are really simple. Not only do they
expose relatively few properties, they also support a limited number of events, and you don't
usually write much code to manage them.
CommandButton Controls in VB6
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, as in this
fragment:
Private Sub Command1_Click()
' Save data, then unload the current form.
Call SaveDataToDisk
Unload Me
End Sub
You can use two other properties at design time to modify the behavior of a CommandButton
control. You can set the Default property to True if it's the default push button for the form
(the button that receives a click when the user presses the Enter keyusually the OK or Save
button). Similarly, you can set the Cancel property to True if you want to associate the button
with the Escape key.
The only relevant CommandButton's run-time property is Value, which sets or returns the
state of the control (True if pressed, False otherwise). Value is also the default property for
this type of control. In most cases, you don't need to query this property because if you're
-
8/12/2019 Visual Basic Notes1
24/36
Visual Basic
Mrs. Poornima Shankar. Page 24
inside a button's Click event you can be sure that the button is being activated. The Value
property is useful only for programmatically clicking a button:
This fires the button's Click event.
Command1.Value = True
The CommandButton control supports the usual set of keyboard and mouse events
(KeyDown, KeyPress, KeyUp, MouseDown, MouseMove, MouseUp, but not the DblClick
event) and also the GotFocus and LostFocus events, but you'll rarely have to write code in the
corresponding event procedures.
Properties of a CommandButton control
To display text on a CommandButton control, set its Captionproperty. An event can be activated by clicking on the CommandButton. To set the background colour of the CommandButton, select a colour in theBackColor property.
To set the text colour set the Forecolor property. Font for the CommandButton control can be selected using the Font property. To enable or disable the buttons set the Enabled property to True or False To make visible or invisible the buttons at run time, set the Visible property toTrue or False.
Tooltips can be added to a button by setting a text to the Tooltip property ofthe CommandButton.
A button click event is handled whenever a command button is clicked. To add a clickevent handler, double click the button at design time, which adds a subroutine like the
one given below.
Private Sub Command1_Click( )
..................
End Sub
OptionButton Controls in VB6
-
8/12/2019 Visual Basic Notes1
25/36
Visual Basic
Mrs. Poornima Shankar. Page 25
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.
Preliminary operations for an OptionButton control are similar to those already described for
CheckBox controls. You set an OptionButton control's Caption property to a meaningful
string, and if you want you can change its Alignment property to make the control right
aligned. If the control is the one in its group that's in the selected state, you also set its
Valueproperty to True. (The OptionButton's Value property is a Boolean value because only
two states are possible.) Value is the default property for this control.
At run time, you typically query the control's Value property to learn which button in its
group has been selected. Let's say you have three OptionButton controls, named optWeekly,
optMonthly, and optYearly. You can test which one has been selected by the user as follows:
If optWeekly.Value Then
' User prefers weekly frequency.
ElseIf optMonthly.Value Then
' User prefers monthly frequency.
ElseIf optYearly.Value Then
' User prefers yearly frequency.
End If
Strictly speaking, you can avoid the test for the last OptionButton control in its group because
all choices are supposed to be mutually exclusive. But the approach I just showed you
increases the code's readability.
A group of OptionButton controls is often hosted in a Frame control. This is necessary when
there are other groups of OptionButton controls on the form. As far as Visual Basic is
concerned, all the OptionButton controls on a form's surface belong to the same group of
mutually exclusive selections, even if the controls are placed at the opposite corners of the
window. The only way to tell Visual Basic which controls belong to which group is by
gathering them inside a Frame control. Actually, you can group your controls within any
-
8/12/2019 Visual Basic Notes1
26/36
Visual Basic
Mrs. Poornima Shankar. Page 26
control that can work as a containerPictureBox, for examplebut Frame controls are often
the most reasonable choice.
The PictureBox Control
PictureBox controls are among the most powerful and complex items in the Visual Basic
Toolbox window. In a sense, these controls are more similar to forms than to other controls.
For example, PictureBox controls support all the properties related to graphic output,
including AutoRedraw, ClipControls, HasDC, FontTransparent, CurrentX, CurrentY, and all
the Draw, Fill, and Scale properties. PictureBox controls also support all graphic methods,
such as Cls, PSet, Point, Line, and Circle and conversion methods, such as ScaleX, ScaleY,
TextWidth, and TextHeight. In other words, all the techniques that I described for forms canalso be used for PictureBox controls (and therefore won't be covered again in this section).
Loading images
Once you place a PictureBox on a form, you might want to load an image in it, which you do
by setting the Picture property in the Properties window. You can load images in many
different graphic formats, including bitmaps (BMP), device independent bitmaps (DIB),
metafiles (WMF), enhanced metafiles (EMF), GIF and JPEG compressed files, and icons
(ICO and CUR). You can decide whether a control should display a border, resetting the
BorderStyle to 0-None if necessary. Another property that comes handy in this phase is
AutoSize: Set it to True and let the control automatically resize itself to fit the assigned
image.
You might want to set the Align property of a PictureBox control to something other than the
0-None value. By doing that, you attach the control to one of the four form borders and have
Visual Basic automatically move and resize the PictureBox control when the form is resized.
PictureBox controls expose a Resize event, so you can trap it if you need to move and resize
its child controls too.
You can do more interesting things at run time. To begin with, you can programmatically
load any image in the control using the LoadPicture function:
Picture1.Picture = LoadPicture("c:\windows\setup.bmp")
-
8/12/2019 Visual Basic Notes1
27/36
Visual Basic
Mrs. Poornima Shankar. Page 27
and you can clear the current image using either one of the following statements:
' These are equivalent.
Picture1.Picture = LoadPicture("")
Set Picture1.Picture = Nothing
The LoadPicture function has been extended in Visual Basic 6 to support icon files
containing multiple icons. The new syntax is the following:
LoadPicture(filename, [size], [colordepth], [x], [y])
where values in square brackets are optional. If filename is an icon file, you can select a
particular icon using the size or colordepth arguments. Valid sizes are 0-vbLPSmall, 1-
vbLPLarge (system icons whose sizes depend on the video driver), 2-vbLPSmallShell, 3-
vbLPLargeShell (shell icons whose dimensions are affected by the Caption Button property
as set in the Appearance tab in the screen's Properties dialog box), and 4-vbLPCustom (size is
determined by x and y). Valid color depths are 0-vbLPDefault (the icon in the file that best
matches current screen settings), 1-vbLPMonochrome, 2-vbLPVGAColor (16 colors), and 3-
vbLPColor (256 colors).
You can copy an image from one PictureBox control to another by assigning the target
control's Picture property:
Picture2.Picture = Picture1.Picture
The Image Control
Image controls are far less complex than PictureBox controls. They don't support graphical
methods or the AutoRedraw and the ClipControls properties, and they can't work as
containers, just to hint at their biggest limitations. Nevertheless, you should always strive to
use Image controls instead of PictureBox controls because they load faster and consume less
memory and system resources. Remember that Image controls are windowless objects that
are actually managed by Visual Basic without creating a Windows object. Image controls can
load bitmaps and JPEG and GIF images.
-
8/12/2019 Visual Basic Notes1
28/36
Visual Basic
Mrs. Poornima Shankar. Page 28
When you're working with an Image control, you typically load a bitmap into its Picture
property either at design time or at run time using the LoadPicture function. Image controls
don't expose the AutoSize property because by default they resize to display the contained
image (as it happens with PictureBox controls set at AutoSize = True). On the other hand,
Image controls support a Stretch property that, if True, resizes the image (distorting it if
necessary) to fit the control. In a sense, the Stretch property somewhat remedies the lack of
the PaintPicture method for this control. In fact, you can zoom in to or reduce an image by
loading it in an Image control and then setting its Stretch property to True to change its width
and height:
' Load a bitmap.
Image1.Stretch = False
Image1.Picture = LoadPicture("c:\windows\setup.bmp")
' Reduce it by a factor of two.
Image1.Stretch = True
Image1.Move 0, 0, Image1.Width / 2, Image1.Width / 2
Image controls support all the usual mouse events. For this reason, many Visual Basic
developers have used Image controls to simulate graphical buttons and toolbars. Now that
Visual Basic natively supports these controls, you'd probably better use Image controls only
for what they were originally intended
The Timer Control
A 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'sactions. 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. Therefore, remember to set this property to a suitable
value in the Properties window or in the Form_Load event procedure:
-
8/12/2019 Visual Basic Notes1
29/36
Visual Basic
Mrs. Poornima Shankar. Page 29
Private Sub Form_Load()
Timer1.Interval = 500 ' Fire two Timer events per second.
End Sub
Using ListBox and ComboBox Controls In Visual Basic 6
ListBox and ComboBox controls present a set of choices that are displayed vertically in a
column. If the number of items exceed the value that be displayed, scroll bars will
automatically appear on the control. These scroll bars can be scrolled up and down or left to
right through the list.
Using the ComboBox
A ComboBox combines the features of a TextBox and a ListBox. This enables the user to
select either by typing text into the ComboBox or by selecting an item from the list. There are
three types of ComboBox styles that are represented as shown below.
Dropdown
combo
Simple combo Dropdown list
Dropdown Combo (style 0) Simple Combo (style 1) Dropdown List (style 2)
The Simple Combo box displays an edit area with an attached list box always visible
immediately below the edit area. A simple combo box displays the contents of its list all the
time. The user can select an item from the list or type an item in the edit box portion of the
combo box. A scroll bar is displayed beside the list if there are too many items to be
displayed in the list box area.
-
8/12/2019 Visual Basic Notes1
30/36
Visual Basic
Mrs. Poornima Shankar. Page 30
The Dropdown Combo box first appears as only an edit area with a down arrow button at the
right. The list portion stays hidden until the user clicks the down-arrow button to drop down
the list portion. The user can either select a value from the list or type a value in the edit area.
The Dropdown list combo box turns the combo box into a Dropdown list box. At run time ,
the control looks like the Dropdown combo box. The user could click the down arrow to view
the list. The difference between Dropdown combo & Dropdown list combo is that the edit
area in the Dropdown list combo is disabled. The user can only select an item and cannot type
anything in the edit area. Anyway this area displays the selected item
Picture Box Animation
Picture Animation is always an interesting and exciting part of programming. Althoughvisual basic is not designed to handle advance animations, you can still create someinteresting animated effects if you put in some hard thinking. There are many ways to createanimated effects in VB6, but for a start we will focus on some easy methods.
The simplest way to create animation is to set the VISIBLE property of a group of images orpictures or texts and labels to true or false by triggering a set of events such as clicking abutton. Let's examine the following example:
This is a program that create the illusion of moving the jet plane in four directions, North,
South ,East, West. In order to do this, insert five images of the same picture into the form. Setthe visible property of the image in the center to be true while the rest set to false. On start-up, a user will only be able to see the image in the center. Next, insert four command buttonsinto the form and change the labels to Move North, Move East, Move West and Move Southrespectively. Double click on the move north button and key in the following procedure:
Sub Command1_click( )
Image1.Visible = FalseImage3.Visible = TrueImage2.Visible = False
Image4.Visible = FalseImage5.Visible = False
End Sub
By clicking on the move north button, only image 3 is displayed. This will give an illusionthat the jet plane has moved north. Key in similar procedures by double clicking othercommand buttons. You can also insert an addition command button and label it as Reset andkey in the following codes:
Image1.Visible = True
Image3.Visible = FalseImage2.Visible = False
-
8/12/2019 Visual Basic Notes1
31/36
Visual Basic
Mrs. Poornima Shankar. Page 31
Image4.Visible = FalseImage5.Visible = False
Clicking on the reset button will make the image in the center visible again while otherimages become invisible, this will give the false impression that the jet plane has move back
to the original position
PICTURE ANIMATION PROGRAM:PROJECT ---COMPONENTS--- CONTROLS TAB--- MICROSOFT WINDOWSCOMMON CONTROL 6.0
IMAGE LIST:CLICK THE RIGHT MOUSE BUTTONSELECT PROPERTIESSELECT IMAGES TABINSERT PICTURE ONE BY ONE
SELECT PICTURE OR IMAGE CONTROL , TIMER , COMMAND BUTTON
TIMER:IT IS USED TO RUN THE LOOP INFINITELYIT IS USED TO SET THE DELAY.DESIGN TIME PROPERTY SETTING:timer-----INTERVAL ---500 ( HALF SECOND)enabled --- false
Dim x As Integer
Private Sub Command1_Click()Timer1.Enabled = TrueCommand1.Visible = False
End Sub
Private Sub Timer1_Timer()x = x + 1
If x = 1 ThenImage1.Picture = ImageList1.ListImages(1).PictureElseIf x = 2 ThenImage1.Picture = ImageList1.ListImages(2).PictureElseIf x = 3 ThenImage1.Picture = ImageList1.ListImages(3).PictureElseIf x = 4 Thenx = 0End If
End Sub
-
8/12/2019 Visual Basic Notes1
32/36
Visual Basic
Mrs. Poornima Shankar. Page 32
Control Structures in Visual Basic 6.0
Control Statements are used to control the flow of program's execution. Visual Basic supports
control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such
as Do While...Loop, While...Wend, For...Next etc method.
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition isTrue; otherwise the action is skipped.
Syntax of the If...Then selection
If Then
statementEnd If
e.g.: If average>75 ThentxtGrade.Text = "A"End If
If...Then...Else selection structure
The If...Then...Else selection structure allows the programmer to specify that a differentaction is to be performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If ThenstatementsElsestatementsEnd If
e.g.: If average>50 ThentxtGrade.Text = "Pass"
ElsetxtGrade.Text = "Fail"End If
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Elseselection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
-
8/12/2019 Visual Basic Notes1
33/36
Visual Basic
Mrs. Poornima Shankar. Page 33
Method 1
If < condition 1 > ThenstatementsElseIf < condition 2 > Then
statementsElseIf < condition 3 > ThenstatementsElseStatementsEnd If
Method 2
If < condition 1 > Thenstatements
ElseIf < condition 2 > ThenstatementsElseIf < condition 3 > ThenstatementsElseStatementsEnd IfEnd IfEndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 ThentxtGrade.Text = "A"ElseIf average > 65 ThentxtGrade.Text = "B"ElseIf average > 55 ThentxtGrade.text = "C"ElseIf average > 45 Then
txtGrade.Text = "S"ElsetxtGrade.Text = "F"End If
-
8/12/2019 Visual Basic Notes1
34/36
Visual Basic
Mrs. Poornima Shankar. Page 34
Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a singleblock of statements from among multiple block of statements. Select...case is moreconvenient to use than the If...Else...End If. The following program block illustrate the
working of Select...Case.
Syntax of the Select...Case selection structure
Select Case IndexCase 0StatementsCase 1StatementsEnd Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.TextSelect Case averageCase 100 To 75txtGrade.Text ="A"Case 74 To 65txtGrade.Text ="B"
Case 64 To 55txtGrade.Text ="C"Case 54 To 45txtGrade.Text ="S"Case 44 To 0txtGrade.Text ="F"Case ElseMsgBox "Invalid average marks"End Select
Loops (Repetition Structures) in Visual Basic 6
A repetition structure allows the programmer to that an action is to be repeated until givencondition is true.
Do While... Loop Statement
The Do While...Loopis used to execute statements until a certain condition is met. The
following Do Loop counts from 1 to 100.
Dim number As Integernumber = 1Do While number
-
8/12/2019 Visual Basic Notes1
35/36
Visual Basic
Mrs. Poornima Shankar. Page 35
number = number + 1Loop
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition istested; if condition is True, then the statements are executed. When it gets to the Loop it goes
back to the Do and tests condition again. If condition is False on the first pass, the statementsare never executed.
While... Wend Statement
A While...Wendstatement behaves like the Do While...Loopstatement. The followingWhile...Wendcounts from 1 to 100
Dim number As Integer
number = 1
While number 1000number = number + 1
Print numberLoop
-
8/12/2019 Visual Basic Notes1
36/36
Visual Basic
Numbers between 1 to 1000 will be displayed on the form as soon as you click on thecommand button.
The For...Next Loop
The For...NextLoop is another way to make loops in Visual Basic. For...Nextrepetitionstructure handles all the details of counter-controlled repetition. The following loop countsthe numbers from 1 to 100:
Dim x As IntegerFor x = 1 To 50Print x
Next
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2Print x
Next
The following loop counts numbers as 1, 3, 5, 7..etc
The above coding will display numbers vertically on the form. In order to display numbershorizontally the following method can be used.
For x = 1 To 50Print x & Space$ (2);
Next
To increase the space between the numbers increase the value inside the brackets after the &Space$.
Following example is a For...Nextrepetition structure which is with the If condition used.
Dim number As IntegerFor number = 1 To 10If number = 4 Then
Print "This is number 4"ElsePrint numberEnd If
Next
In the output instead of number 4 you will get the "This is number 4".
top related