You are on page 1of 214

Visual Basic

OOP



))


((








...
...

Visual Basic
OOP

2002

* " Visual Basic "OOP



.
* Windows Visual Basic

.
*

.
*
.
* %100 .


-----------------------------------------------------
---------------------------------------------------
:
: 2 -------------------------- Visual Basic
2 ------------------------------------------- IDE
3 ---------------------------------
9 ---------------------------------
12 ---------------------------------------------
12 ------------------------------------------------
: 12 -----------------------------
: 12 ---------------------------
: 13 ----------------------------
: 14 ---------------------------
: 15 -----------------------
: 16 --------------------------------
: 17--------------------------------
17 ------------------------------------------------
19 ------------------------------------- Name
19 ------------------------------------
20 ------------------------------------------
21 ------------------------------------------ Font
22 ----------------------------------------------
23 --------------------------------------------
24 ---------------------------------------
25 ------------------------------ RightToLeft
27 -------------------------------------hWnd
27 ----------------------------------------------
28 ---------------------------------------------------
28 ---------------------------------------------- Move
29 ----------------------------------------- SetFocus

30 -------------------------------------------- ZOrder
30 ------------------------------------------- Refresh
31 -------------------------------------------------
32 ------------------------------------------------
34 -----------------------------------------------
35 --------------------------------------
37 ------------------------------------- Change
37 -------------------------------------------------------
37 --------------------------------------------
43 -----------------------------------------------
48 ---------------------------------------------
52 --------------------------------------------- Menus
53 ----------------------------------------------------
53 ------------------------------------------ Label
54 ---------------------------------------- TextBox
60 ------------------------------ Command Button
60 ------------------------------------ CheckBox
61 ---------------------------------- OptionButton
61 --------------------------------------- ListBox
64 ----------------------------------- ComboBox
64 ------------------------------------ PictureBox
64 ------------------------------------------ Image
65 --------------------------------- ScrollBars
66 ----------------------------------------------
68 -------------------------------------------------
: 70 ---------------------------- BASIC
70 --------------------------------------------------
70 ----------------------------------
75 ---------------------------------------------------
83 ------------------------------------------------------
85 ----------------------------------------------
85 -------------------------------------------- Enum
87 ------------------------------------- UDT
89 --------------------------------------------------

93 --------------------------------------------------
96 ---------------------------------------------------
98 ---------------------------------
100 ----------------------------------------
101 -----------------------------
103 ----------------------------------------
103 -------------------------------------- IF
105 --------------------------------- Select
107 -----------------------------------------
110 ---------------------------------------------------
P-Code 110 ---------------------------------- Native Code
112 ----------------------- Advanced Optimization
: VB 114 ------------------------------ VBA
114 ------------------------------------------------
114 ----------------------------------------
117 --------------------------------------------
118 --------------------------------------------
118 -------------------------------------------------
120 -----------------------------------------------
120 ----------------------------------------
122 ----------------------------------------
123 --------------------------------------------
123 ------------------------------------------------
126 ----------------------------------------
126 --------------------------------------
130 ------------------------------------
130 -----------------------------------
131 ---------------------------------------
131 -------------------------------------
133 ---------------------------
133 ---------------------------------------------
138 ------------------------------------------------------
139 ----------------------------------------- App
140 --------------------------------- Clipboard

142 ----------------------------------- Screen


142 -------------------------------------- Printer
144 --------------------------------------------------
144 -------------------------------------------------
147 -------------------------------------------------- Err
: 149 ---------------- OOP
149 ------------------------------------------------- OOP
OOP 150 -----------------------------------------------
151 ---------------------------------------------- OOP
152 -------------------------------------
153 ---------------------------------------------------------
153 ---------------------------------------------
157 ------------------------------------------------
158 ----------------------------------------------
162 ----------------------------------------------
165 ------------------------------------------------
165 --------------------------
167 -----------------------------------
168 -------------------------------------
171 -------------------------------------------- Binding
173 ----------------------------------------
174 -------------------------
: 175 --------------------
175 ---------------------------------- Polymorphism
176 ---------------------------------------------
178 ---------------------------------------------- Inheritance
180 --------------------------- Visual Basic
" " 183 -------------------------------------
184 ------------------------------------- Delegation
186 --------------------------------------------
188 -------------------------- Subclassing
189 ---------------------------------------------------
190 --------------------------------------
194 ------------------ Collection Classes

:
: 0 ---------------------
0 -----------------------------------------
0 -------------------------------------------
0 --------------------------------------------------- SQL
: 0 --------------------------- ADO
0 --------------------------------------------------- Connection
0 ---------------------------------------------------- Recordset
0 --------------------------------------------------- Command
: 0 ---------------------------------
0 -------------------------------------------------------- DataGrid
0 --------------------------------------------------------- FlexGrid
DataCombo 0 ------------------------------------- DataList
0 --------------------------------------------------------
:
: 0 ------------------------------ API
0 --------------------------------------------- Windows
0 -------------------------------------------------------
API 0 --------------------------------------
: 0 --------------------
0 -------------------------------------------------------
0 ------------------------------------------
0 --------------------------------------------------------
0 -----------------------------------
: 0 ------------------ 1 COM
0 ----------------------------------------------------- COM
0 ------------------------------------------------ ActiveX EXE
0 ------------------------------------------------ ActiveX DLL
: 0 ------------------- 2 COM
0 ----------------------------------------------- ActiveX OCX
0 ----------------------------------------- Threading
0 -------------------------------------------- DCOM

:
: DHTML 0 ---------------
0 ------------------------------------------------ VBScript
0 -------------------------------------------------- DHTML
: ASP 0 --------------------
0 ------------------------------------------------------- IIS
0 ----------------------------------------------------------- ASP
:1 0 --------------------- Visual Basic
0 -------------------------------------------------
0 ----------------------------------------------

" "Visual Basic




.
vb4arab.com
Visual Basic :


Visual Basic.
-vb4arab
.
JAVA C++ -
.OOP
-
.
-Hardcore Visual Basic
.

.

. .

.




.Visual Basic

VB1 -
Form Designer Locate Print Color
- - .
Visual Basic
Visual Basic - -
.BASIC
Mouse

.Code Window
" " Visual Basic
- - ! Visual
Basic Buttons TextBoxes
DataBases
-
Visual Basic .
Visual Basic Memory Management
-
Pointers Visual Basic
K64
Visual Basic
- !
Visual Basic
Visual
Basic
.


- :
Visual Basic Visual Basic Visual
Basic .Visual Basic
Visual
Basic -
Visual Basic Visual Basic
Visual Basic .
Visual Basic
.


Visual Basic

Visual Basic MSDN
. -

.
Visual Basic

.... . :
: Visual Basic
Visual Basic
BASIC
OOP .Visual Basic
:
DataBases API
COM .DCOM
: Refresh
Visual Basic

Visual Basic .


Reference
MSDN .
....
. -
.... .
MSDN
....
.

Visual Basic.NET

.NET Microsoft
Beta .Visual Studio.NET
Visual Basic VB6 Visual Basic
Visual Basic.NET
Visual Basic Syntax . Visual Basic.NET
Microsoft
VB1 .VB6 Visual Basic.NET

VB6 .C# Visual Basic.NET
12 :
Visual Basic.NET Visual Basic.NET
Visual Basic.NET Visual
.Basic.NET
VB6
HardDisk Visual
Basic.NET

- OOP
nTied Applications DCOM
.



:
:

Visual Basic

BASIC VB .VBA
OOP :
Encapsulation Polymorphism .Inheritance
:

DataBases Data Access
SQL ADO
.
:

Visual Basic API

" "
. COM
ActiveX DLL ActiveX EXE ActiveX OCX
.DCOM
:

DHTML VBScript
Client Server IIS
.ASP


.
Tahoma
UNICODE



Codes.ZIP Download
. ] [
]... [ESC] [ENTER .
-


! 9485938



.


.


.

- -
.

.

2002

Visual Basic
.Visual Basic
Visual Basic Visual Basic
Visual Basic
Visual Basic for Application
.VBA Visual Basic
.
Visual Basic
Visual Basic BASIC
Visual Basic Visual Basic
Visual Basic -
.

IDE

Windows
.Notepad -
Notepad .Visual Basic Visual Basic

Integrated Development Environment -IDE
. -
Debugging
... .1-1

:1-1 .Visual Basic


-VB5
.
-
.
1-1
Child Windows Menus
Toolbars :


Visual Basic "
"Data View .

Multiple Document Interface
MDI
.
:

4
New Project
Visual Basic
.
.... ActiveX DLL ActiveX EXE Standard EXE . Standard EXE
Open ] .[ENTER
Visual Basic Standard EXE
!
- - Visual
Basic Dont show this
dialog in the future
.
:


Options Tools
Environment Prompt for
.project

Form Designer
Visual Basic Visual Basic
.Form1

Mouse Visual
.Programming Languages
Macro 5.25 .Tapes

.Paint
.
:


.
.

5
Toolbox

. Toolbox 2-1
20 Visual Basic
- ActiveX Controls
. 20 21 Buttons

Pointer .

.

:2-1 .Toolbox


Add Tab
.
Drag & Drop
.
Delete Tab
General .

Toolbox .View
Properties Windows

6
Form .... .
Properties Window View
].[F4
Visual Basic ComboBox
.
- -
.
Alphabetic .Categorized

.
Caption Visible
BackColor
" "... Dialog Box
.Font
Project Explorer


.
] .[F1

Project Explorer View ].[Ctrl +R
Code Window
Visual Basic .

.

Unicode Windows 2000, XP

Font ) .Courier New (Arabic
Editor Format
Options Options .Tools

7

] .[F7

Procedure View

ComboBoxes

) (General

.
Form Layout
Form Layout Window View

.
Resolutions .
Resolution
Guide .
Immediate Window
Visual Basic
.
] [ENTER .
Immediate Window .View
Object Browser

Visual Basic .

.


Help .
Object Browser View ].[F2

8
Local Window
Run Time
Design Time
. Local
Variables Procedure
Pause . Objects
" "+
.
Local Window .View
:

Run Time
] [F5 Design Time
.
Pause Time Break
.

Watches Window
.
.
- True
.
Debugging
%90 Bugs .
Watch Window View
Add Watch Debug -View
.

.Global
Call Stack
.

.Recursion

9

Call Stack View ].[Ctrl+L
Data View
Data View Window
View .Standard Toolbar
IDE
Visual Basic .
! -

.... ORACLE MS-Access MS-SQL Server :.

" " - !



.MSDN -
:
:File


.Binary VB6

.Multiple Projects
:Edit
.

.Data View
.Code Window

10
:View
" "
.
:Project

Forms Module Classes
.... . ActiveX Controls
Components ActiveX DLL
.References
:Format



. Lock Controls

.
:Debug
.
Step Into Step Over
Step Out Run
.to Cursor BreakPoints

.
:Run

Break .End
Start with Full Compile Start
.

11
:Query
VB5
Professional Edition Enterprise Edition .VB6
SQL
.Microsoft Query Builder
:Diagram
VB5
.
SQL Server .ORACLE
:Tools
Menu Editor
Add Procedure ... IDE
Options Options
.IDE
:Add-Ins
Add-
Ins .
.
:Window
Visual
Basic Windows
-
Windows .
:Help
Visual Basic
Microsoft Developer
Network .MSDN

12



. .
MS-Office
Customize
. ToolBox
.

:
Visual Basic
.
.

.


- Visual Basic
. Software
Engineering .
.

:
.
New Project File .Standard EXE

13
Windows
.EXE

Project Name Project Properties
Project1 Properties .View
.MyFirstProgram
:

.
MyFirstProgram
.Properties

Save Project File


Folder
. VBP
*.FRM *.BAS
.... *.CLS.

:
Visual Basic
.
.

.Paint
ToolBox Label
CommandButton TextBoxes Line
:3-1

:3-1 .

14
.

:

Name
Caption
Name
Caption
Name
Caption
Name
Caption
Name
Caption

frmMain
" "
cmdMultiply
""
lblProduct
""0
txtFirst
""0
txtSecond
""0

Visual Basic
frm
cmd txt ....

Visual Basic.

: .


.
Code Window :
)(Private Sub cmdMultiply_Click
End Sub

15

Click .cmdMultiply
Event Driven Programming
.
:
)(Private Sub cmdMultiply_Click
)lblProduct.Caption = CDbl(txtFirst.Text) * CDbl(txtSecond.Text
End Sub


-

.

:
] [F5 .
2 5
"" 10 .

" " ""

- ""
.
Run Time Errors
Visual Basic :
* = 5


:

16

)(Private Sub cmdMultiply_Click


'
'
If IsNumeric(txtFirst.Text) = True And IsNumeric(txtSecond.Text) = True Then
)lblProduct.Caption = CDbl(txtFirst.Text) * CDbl(txtSecond.Text
Else
"! " MsgBox
End If
End Sub

:

Compiling
Executable EXE Make
MyFirstProgram.EXE .File
:

Compiling
Linking .EXE Visual
Basic Compiling .Linking


Windows
Visual Basic DLL Visual Basic
.MSVBVM60.DLL
EXE .Visual Basic

17


Form Visual Basic Window

.Windows Controls
.
Visual Basic Built-in
- Controls -Intrinsic Controls
.2-1 Visual Basic

MSVBVM60.DLL .
ActiveX Controls .OCX

Components .Project
.Objects
- -Members
: Properties Methods .Events
Visual Basic

.

.

Caption
.Enabled

18

:
= Text1.Text
PictureBox1.BackColor = 0
Label1.Caption = Text1.Text

With
:
With Text1
" " = .Text
.Font.Bold = True
.BackColor = vbBlack
.ForeColor = vbWhite
End With

Default Property
.
Caption Text
:
= Label1.Caption
= Label1
Text1 = Text1.Text


Me :

= Form1.Caption
= Me.Caption
= Caption


BorderStyle

19
- CurrentX -
.
- hWnd
Read Only Properties
.
Write Only Properties
.

.Name

Name

.
.

.
Visual Basic Form2 Form1
.... Label1 .
:
. 40. & .... " . .



Visible Timer
.
Left Top

.
ScaleMode .

20
Twip .

Center in Form Format
:
Command1.Left = (Me.ScaleWidth - Command1.Width) / 2
Command1.Top = (Me.ScaleHeight - Command1.Height) / 2

Height Width
.
Height ComboBox Style
0 Height
Font . -ListBox
Height
x
.


Parent Container Reference
Parent .Container
Parent Container
:
PictureBox
Set Command1.Container = Picture1

Set

Set .


-
Caption :

21
" " = Command1.Parent.Caption


Parent Container .

Font

.
.Font
:Font
With Label1
.Font.Name = Tahoma
.Font.Bold = True
.Font.Size = 20
End With

Font
:
Set Label1.Font = Label2.Font

Font
Label2 Font Label1 Font
Label2
Label1 :
Label1
Label2.Font.Size = 20

Font .

22
:

Font.Name
Visual Basic

Visual Basic .
True Type Font.Size
Visual Basic
:
"Label2.Font.Name = "MS SystemEx
Label2.Font.Size = 20
Print Label2.Font.Size 15

Visual Basic
.... FontBold FontSize FontName VB6
.


BackColor ForeColor .
ScorllBar
. Label
BackColor BackStyle .1-Opaque
CommandButton
Style 1Graphical
ForeColor .
:
Standard Color .Custom Color

Appearance Display Properties
Windows .

23
.Standard Color


" " .

:
Me.BackColor = vbGreen
Me.BackColor = vbBlue

QBColor
:MS-DOS
)Me.BackColor = QBColor (0
)Me.ForeColor = QBColor (15

RGB :
)Me.BackColor = RGB (255, 0, 0

16
:
Me.BackColor = 4234232
Me.ForeColor = &H53FF2


QBColor RGB

.

Windows ][TAB
. Focus

24
TabStop .TabIndex
TabStop
] [TAB TabIndex
.
:

TabStop False

.

MousePointer MouseIcon
.Mouse Cursor 16 MousePointer
99-
Custom MouseIcon
:
Command1.MousePointer = vbCustom
)Command1.MouseIcon = LoadPicture (C:\Test.ICO

.
Visual Basic
Screen :
Screen.MousePointer = 2
Command1.MousePointer = 5

Visual Basic
Visual Basic
Visual Basic MousePointer :
MousePointer Screen 0-Default Visual Basic MousePointer

.

25
MousePointer Screen 0-Default MousePointer 0-Default
MousePointer .
MousePointer Screen 0-Default MousePointer 0-Default
MousePointer
.



:
)(Private Sub Command1_Click

Screen.MouseIcon = vbHourglass


Screen.MousePointer = vbDefault
End Sub

RightToLeft
VB1 VB4 -
VB5
RightToLeft
. RightToLeft
Visual Basic
.

26
:

Windows 98
Windows
.
API
.

MSVBVM60.DLL
VBAME.DLL
System Directory

. True
.

:
)(Private Sub Form_Load
Dim Ctrl As Control
On Error Resume Next
For Each Ctrl In Controls
If TypeOf Ctrl Is Line Then
Ctrl.X1 = Ctrl.Container.ScaleWidth - Ctrl.X1
Ctrl.X2 = Ctrl.Container.ScaleWidth - Ctrl.X2
Else
Ctrl.Left = Ctrl.Container.ScaleWidth - Ctrl.Left - Ctrl.Width
End If
If Ctrl.Alignment = 1 Then
Ctrl.Alignment = 0
ElseIf Ctrl.Alignment = 0 Then
Ctrl.Alignment = 1
End If
Ctrl.RightToLeft = True
Next
RightToLeft = True
Err.Clear

27
End Sub

hWnd

Read Only Propeties


.Long Visual Basic
API
.
Standard Controls
Windowless Controls .
TextBox Visual Basic
Windows
. Windows
.Window Handle
hWnd .
Visual Basic

Visual Basic Visual Basic
.Windows
Windowless Controls
Visual Basic
.hWnd
:
Line Shape Timer Label Image
.hWnd
System Resources .
ActiveX Controls Standard Controls
.Windowless Controls
hWnd
hWnd .

Visible

28
.
Enabled
. Tag
String - -
. Index
Control Array "
".

Appearance 3-D
BorderStyle
Align
.
Windows

ToolTip
.ToolTipText
DragMode DragIcon
.... LinkItem LinkMode LinkTopic
.
Compatibility

.


. Methods Functions
Subs .
:

Move

Height Top Left Width


Move . :

29

Form1.Left = 100
Form1.Top = 200
Form1.Height = 300
Form1.Width = 400

4 Form_Resize 4
:Move
Form1.Move 100, 200, 300, 400


:
Form1.Move 100, 200
Form1.Move 100, , 300

SetFocus
SetFocus .

.Run Time Error Visible
Enabled :
If Text1.Visible = True And Text1.Enabled = True Then
Text1.SetFocus
End If


:LostFocus
)(Private Sub Text1_LostFocus
If Trim(Text1.Text) = "" Then
Text1.SetFocus
End If
End Sub

30

Form_Load
:
)(Private Sub Form_Load
Me.Show
Text1.SetFocus
End Sub

ZOrder

ZOrder
:1
0
Command1.Zorder

Command1.Zorder 0
Command1.ZOrder 1

Winodwless Controls -Label


.Standard Controls

.
.

Windows
.

Refresh
.
Visual Basic .
Visual Basic :
)(Private Sub Command1_Click

31
Dim X As Long
For X = 0 To 100000
)Label1.Caption = CStr(X
Label1.Refresh
Next
End Sub

Visual Basic .DoEvents




Processing
.
Bugs Command1
.
!

Event Driven Programming


.

.
. Subs :
_
)( Form_Click
)( Command1_Click

Fire Event


Visual Basic

!

32
Form
.Name
:


%50
.
Click . DblClick
. Click
Value CheckBox
OptionButton Visual Basic Click .
ListIndex ListBox
.ComboBox

Click DblClick Visual
Basic
.
Click .DblClick

:
Dim bDblClick As Boolean
)(Private Sub Form_Click
Dim X As Single
bDblClick = False

X = Timer
Do
DoEvents
If bDblClick Then Exit Sub
Loop Until Timer > X + 0.5

...

33
End Sub
)(Private Sub Form_DblClick
bDblClick = True

...
End Sub


....
MouseDown
MouseMove MouseUp
: Button Shift
X .Y
Button / /
:
_ Private Sub Form_MouseDown(Button As Integer, Shift As Integer,
)X As Single, Y As Single
If Button And vbLeftButton Then
'
End If
If Button And vbRightButton Then
'
End If
If Button And vbMiddleButton Then
'
End If
End Sub

Shift Shift
KeyUp KeyDown "
" . X Y
)(0 0

34
X
Y .
MouseMove
.
Capturing MouseMove
X Y
.
:

Capturing
.

MouseDown MouseUp

-
Visual Basic MouseDown
MouseUp.
Double Click
:
MouseUp <- DblClick <- MouseMove <- Click <- MouseUp <- MouseDown
MouseMove <- .


GotFocus LostFocus
.

.
:



.
.

35


Visual Basic KeyPress
KeyDown .KeyUp
KeyDown Visual Basic
ASCII KeyPress
KeyUp.
KeyPress Visual Basic
] [Ctrl+] [ESCAPE] [BACKSPACE] [ENTER
...
KeyPress KeyDown KeyUp
. KeyPress Integer
KeyAscii
:ASCII
)Private Sub Form_KeyPress(KeyAscii As Integer
Print Chr$(KeyAscii) & " = " & KeyAscii
End Sub

KeyAscii

:Capital
)Private Sub Text1_KeyPress(KeyAscii As Integer
)))KeyAscii = Asc(UCase(Chr$(KeyAscii
End Sub


.
:9 ... 1 0
)Private Sub Text1_KeyPress(KeyAscii As Integer
If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0
End If
End Sub

36
:

Asc .Chr$

.ASCII

KeyDown KeyUp KeyCode


Shift ] [CTRL] [SHIFT ] [ALT
- :
)Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer
If Shift And vbShiftMask Then
] [SHIFT '
End If
If Shift And vbCtrlMask Then
] [CTRL '
End If
If Shift And vbAltMask Then
] [ALT '
End If
End Sub

- -KeyCode
KeyAscii
Small Letter
.... @#% .... .
Capital .... C B A .
KeyCode
.KeyAscii
KeyDown KeyPress KeyUp



Visual Basic!
KeyPreview True
False

37

.

Change
Change
Caption .Text
Value CheckBox
OptionButton Visual Basic
.

Visual Basic
Visual Basic Form1
.VB1
"
"
!

Templates Form Templates

. Add
Form Project .


- \VB98\Template\Forms
Environment -Options
Template .



. .BorderStyle
0-None Splash Screen

38
TitleBar

] [Ctrl+Alt+Del ] [Ctrl+Shift+Esc
. 2-Sizable

- . 1-Fixed Single 3-Fixed Dailog

Dialog Boxes Windows
Maximize Minimize
. 4-Fixed ToolWindow 5-Sizable
ToolWindow .
0-None
3-D
Caption ControlBox False
3-Fixed Dailog .BorderStyle

MaxButtom ControlBox .MinButton
.Caption
2-Center
StartupPosition
Moveable .False ShowInTaskBar
Windows Task Bar "" Start
.
WindowState
.
:
AutoRedraw
True False .

System Resources
800x600 True Color 1406
1 5 9

39
Form_Paint
.True
.... Line Print
.Form_Paint
.... Circle Line
ClipControls False
Visual Basic Clipping region

True .
HasDC Device Context

. Picture
False
hDC
hDC .
Icon Control Box

ShowInTaskbar True ) (None
ControlBox
.True EXE File Icon
Visual Basic
Icon Make
.Project Properties
Picture
JPG GIF DIB BMP :
ICO EMF WMF .CUR

Copy Clipboard
Paste .Edit
LoadPicture :
! )Form1.Picture = LoadPicture (C:\Turki.BMP
Form2.Picture = Form1.Picture Form1

40
:

Picture
:

Print Me.Picture.Height
Print Me.Picture.Width

VB6 LoadPicture Icon


ICO MSDN
LoadPicture SavePicture
:
SavePicture Form1.Picture, C:\Aseeri.BMP

Format SavePicture
GIF JPG
.BMP

:
Image
.... Cirle Line
Picture -
AutoRedraw .True
DrawWidth
Line PSet Circle ForeColor
. DrawStyle
Line Cirlce
FillStyle
.FillColor CurrentX CurrentY
Line Print
.... .
FontTransparent Print
False
BackColor True
.

41
:DrawMode
DrawMode
-Line
. 13-Copy Pen

.

:1-2

)(

)(

)(
:1-2 DrawMode .
) 1-2(

)( )( )(
" "50%
)( DrawMode
.

10011101010

42
Pen Color Screen
Color 15-MergePen DrawMode :

S = S Or P

170 = 10101010
85 = 01010101 15-MergePen:
01010101
10101010
S Or P
10101010 Or 01010101
11111111

=
=
=
=
=

S
P
S
S
S

11111111 .255
MSDN " DrawMode
"Property .Index
:ScaleMode
" "

.ScaleMode 8 Units
1-Twip : 0.567 2-Point 0.72
3-Pixel 4-Character Twips 120
Twips 240 5-Inch 6-Milimeter
7-Centimeter 0-User
.
Width Height Twip
ScaleMode

Twip ScaleMode
ScaleWidth :ScaleHeight
)(Private Sub Form_Paint
Cls
ScaleMode = vbPixels
Print ScaleHeight

43
Print ScaleWidth
End Sub

ScaleWidth ScaleHeight
Width Height
.

:
)(Private Sub Form_Paint
Cls
ScaleMode = vbTwips
Print Height - ScaleHeight
Print Width - ScaleWidth
End Sub

0-User
ScaleHeight ScaleWidth
ScaleLeft .ScaleTop
.


ScaleMode
ScaleX .ScaleY
.
:
Pixels Twips
)Print ScaleX(100, vbPixels, vbTwips

Show Hide
Visible :
Form1.Show Form1.Visible = True
Form1.Hide Form1.Visible = False

44

Cls
CurrentX CurrentY ) (0, 0 Point
) (x, y :
)(Private Sub Form_Load
! '
)Form1.Picture = LoadPicture (C:\Turki.BMP
End Sub
_ Private Sub Form_MouseMove(Button As Integer, Shift As Integer,
)X As Single, Y As Single
)Label1.BackColor = Point(X, Y
))Label1.Caption = Hex$(Point(X, Y
End Sub

PSet ) (X, Y
ForeColor
:

Me.ForeColor = vbBlack
)PSet (0, 0
PSet (500, 500), vbRed

PSet - Step
) (X, Y
CurrentX :CurrentY
)(Private Sub Form_Paint
Dim X As Integer
Cls
Me.CurrentX = 0
Me.CurrentY = 0
For X = 0 To 100

45
)PSet Step(5, 5
Next
End Sub

Line ) (X1, Y1
):(X2, Y2
ForeColor = vbGreen
)Me.Line (0, 0) - (Me.ScaleWidth, Me.ScaleHeight

Me.Line (0, Me.ScaleHeight) - (Me.ScaleWidth, 0), vbRed

) (X1, Y1 CurrentX
CurrentY :
_ Private Sub Form_MouseMove(Button As Integer, Shift As Integer,
)X As Single, Y As Single
)Me.Line - (X, Y
End Sub

Line B
FillStyle :FillColor

ForeColor = vbWhite
Line (0, 0) - (200, 200), , B
Line Step (200, 200), vbBlue, B

:BF

ForeColor = vbWhite
Line (0, 0) - (200, 200), , BF
Line Step (200, 200), vbBlue, BF

Cirlce !
:

46

ForeColor = vbWhite
Circle (Me.ScaleWidth / 2, Me.ScaleHeight / 2), 500
Circle (Me.ScaleWidth / 2, Me.ScaleHeight / 2), 200, vbGreen

BF BF
FillColor .FillStyle
Cirlce
:Radian
Const PI = 3.14

Circle (Me.ScaleWidth / 2, Me.ScaleHeight / 2), 1000, , 0, PI

Circle (Me.ScaleWidth / 2, Me.ScaleHeight / 2), 800, , PI, 0

Circle (Me.ScaleWidth / 2, Me.ScaleHeight / 2), 500, , 0, PI / 2

Circle
Charts
:
Const PI = 3.14
FillStyle = 0
FillColor = vbBlue
)Circle (Me.ScaleWidth / 2, Me.ScaleHeight / 2), 1000, , - (PI), - (PI / 2

Ellipse Ratio
:

Circle (Me.ScaleWidth / 2, Me.ScaleHeight / 2), 1000, , , , 2

PaintPicture VB5
Picture
10!

47



.DrawMode
PaintPicture
.... Codes.ZIP
PaintPicture :
)(Private Sub Form_Paint
Cls
_ PaintPicture Picture1.Picture, 0, 0, lWidth1,
lHeight1, lX2, lY2, lWidth2, lHeight2, iDrawMode
End Sub

Print
Visual Basic BASIC Print
.VB6
";" :Visual Basic

"" "," Print


"" ;"" Print

Print -
. Visual Basic
.BASIC

Print
.Font TextHeight TextWidth

:
Dim sText As String
Font.Size = 20
" " = sText
CurrentX = (ScaleWidth - TextWidth(sText)) / 2
CurrentY = (ScaleHeight - TextHeight(sText)) / 2

48
Print sText


Image
.


Visual Basic
" " .
:
<- (Deactivate) <- Paint <- Activate <- Resize <- Load <- Initialize
.Terminate <- Unload <- QueryUnload
:

Deactivate Paint


... <- Paint <- Activate

:Initialize

Visual Basic
:
Initialize Form2
Dim X As Form2
Set X = New Form2


:
Dim sUserName As String
)(Private Sub Form_Initialize
" " = sUserName

49
End Sub

:Load
Load
:Load
Load Form2

:
Load Form2
Caption
= Form2.Caption

Load

SetFocus .... .
:
)(Private Sub Form_Load
Text1.Text = sUserName
End Sub

:Resize
Resize

:
)(Private Sub Form_Resize
'
_ Command1.Move (Me.ScaleWidth - Command1.Width) / 2,
(Me.ScaleHeight - Command1.Height) / 2
End Sub

50
:Activate
-Resize
.Active Window

.
-
:
)(Private Sub Form_Activate
Label1.Caption = Form2.Text1.Text
End Sub

:Paint

Paint

.
AutoRedraw True Paint
!
:
)(Private Sub Form_Paint
Cls
FillStyle = 0
_ Circle (ScaleWidth / 2, ScaleHeight / 2),
IIf(ScaleWidth < ScaleHeight, ScaleWidth, ScaleHeight) / 2, 0
End Sub

Paint
Paint


Visual Basic
:Resize

51
)(Private Sub Form_Resize
Form_Paint
End Sub


Paint

Resize Fomr_Paint
Visual Basic :Refresh
)(Private Sub Form_Resize
Me.Refresh
End Sub

Paint
Click
GotFocus
.
:Deactivate
Activate
.
Hide Visible .False
:QueryUnload
QueryUnload
.
.UnloadMode
True
Cancel
Control Box " "X :
)Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer
If UnloadMode = vbFormControlMenu Then
Cancel = True

52
End If
End Sub

UnloadMode
.MSDN
:Unload
Unload

Cancel UnloadMode .
:Terminate

" ."OOP

Menus

Visual Basic Menu


Menu Editor
Menu Editor .Tools
Template Menu
Add-In .VB6 Template Manager
Caption
"&"
Alt
Caption " "-
. Name


:
& = mnuFile.Caption
mnuEdit.Enabled = False

53
Visible Enabled
. Checked
. WindowList
.MDI
:Pop-Up Menus
.
.Pop-Up Menu Visual Basic
PopupMenu :
_ Private Sub Form_MouseDown(Button As Integer, Shift As Integer,
)X As Single, Y As Single
If Button And vbRightButton Then
PopupMenu mnuView
End If
End Sub

:
PopupMenu frmMain.mnuHelp


ToolBox :Label

Label
Windowless Controls
Caption "&"


TabIndex ] [Alt
UseMnemonic .False

54
:

"&"
UseMnemonic True .

BorderStyle Alignment
0-Left Justify
1-Right Justify .2-Center WordWrap

. BackStyle
.


Click
ToolTip
.

TextBox

Text Box Windows



.
.Text
True Locked . MaxLength
.
"*"
PasswordChar .
:

PasswordChar
Copy

Visual Basic
.
.

55
MultiLine
ScorllBars .
:

MultiLine True
ScorllBars 0-None 2-Vertical

WordWrap .

Run Time Properties


SelStart
.SelLength
:
)(Private Sub Text1_GotFocus
Text1.SelStart = 0
)Text1.SelLength = Len(Text1.Text
End Sub

.SelText
Text
:
= Text1.SelText


] [TAB ][TAB

TabStop :
)(Private Sub Text1_GotFocus
On Error Resume Next
Dim ctrl As Control
For Each ctrl In Controls
ctrl.TabStop = False

56
Next
Err.Clear
End Sub
)(Private Sub Text1_LostFocus
On Error Resume Next
Dim ctrl As Control
For Each ctrl In Controls
ctrl.TabStop = True
Next
Err.Clear
End Sub

Windows 2000, XP
-

UNICODE Visual Basic ASCII


] [Alt+SHIFT :
_ Declare Function LoadKeyboardLayout Lib "user32" Alias
_ "LoadKeyboardLayoutA" (ByVal pwszKLID As String, ByVal
flags As Long) As Long
)(Sub BeforeCopyOrCut
LoadKeyboardLayout "00000401", 1
End Sub

:

.


.Run Time Error

57

:KeyPress
)Private Sub Text1_KeyPress (KeyAscii As Integer
If KeyAscii < 48 Or KeyAscii > 57 Then

KeyAscii = 0
End If
End Sub


!
:
.Ctrl + V
KeyDown .
!
Visual Basic
!
.
- -
Change
:
Dim OldText As String
Dim OldSelStart As Long
)(Private Sub Text1_GotFocus


OldText = Text1.Text
OldSelStart = Text1.SelStart
End Sub
)(Private Sub Text1_Change
If Not IsNumeric(Text1.Text) Then

58

Text1.Text = OldText
Text1.SelStart = OldSelStart
Else


OldText = Text1.Text
OldSelStart = Text1.SelStart
End If
End Sub


" "
Text1.Text = OldText Visual Basic
Text1_Change !
Recursivly
.Recursion
:
)(Private Sub Text1_Change

Static bExitNow As Boolean
If bExitNow Then Exit Sub
If Not IsNumeric(Text1.Text) Then


bExitNow = True
Text1.Text = OldText
bExitNow = False
Text1.SelStart = OldSelStart
Else


OldText = Text1.Text
OldSelStart = Text1.SelStart

59
End If
End Sub

! Caret
.

.
:
)Private Sub Text1_KeyUp (KeyCode As Integer, Shift As Integer
OldSelStart = Text1.SelStart
End Sub
_ Private Sub Text1_MouseUp (Button As Integer, Shift As Integer,
)X As Single, Y As Single
OldSelStart = Text1.SelStart
End Sub
)Private Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer
OldSelStart = Text1.SelStart
End Sub
)(Private Sub Text1_Click
OldSelStart = Text1.SelStart
End Sub

:
!
!


. Validate Visual Basic
. Validate
CausesValidation
: Text1 X Visual Basic
CausesValidation X True

60
Visual Basic Validate Text1
. :
)Private Sub Text1_Validate(Cancel As Boolean
If Not IsNumeric(Text1.Text) Then

Cancel = True
End If
End Sub

Cancel True
.Text1
LostFocus Validate LostFocus
! )
(Cancel LostFocus

Cancel .

CommandButton
.CommandButton
Default Cancel

] [ENTER ] .[ESC Picture
DisablePicture DownPicture
Style .1-Graphical
:

Caption "&"
Label UseMnemonic
.True

CheckBox

Value 1-Checked 0-UnChecked

61
2-Grayed
False Enabled %100 False
Enabled 2-Grayed


Codes.ZIP .
Click
Value .
DisablePicture Picture DownPicture
Style .1-Graphical

Caption "&"
CommandButton .

OptionButton

OptionButton Radio Button


CheckBox Value True .False
Value True
-
Frame .
DisablePicture Picture DownPicture
Style .1-Graphical
:

Caption "&"
CommandButton .

ListBox

.ScorllBars Sorted
-
.

62
Columns
.
Height
Visual Basic

Visual Basic IntegralHeight .False
List
:AddItem
List1.AddItem
List1.AddItem
List1.AddItem



:
List1.Visible = False
For X = 0 To 10000
List1.AddItem X
Next
List1.Visible = True

- Sorted
-False :
List1.AddItem
, 0 List1.AddItem
, 1 List1.AddItem

.
RemoveItem Clear :
List1.RemoveItem 0
List1.Clear

63

ListIndex 1-
Text
:
List1.ListIndex = 0
Print List1.Text

ListCount
List :
For X = 0 To List1.ListCount
)Print List1.List (0
Next

MultiSelect
1-Simple
] -[Ctrl 2-Extended
Selected
:
)(Private Sub cmdMoveLeft_Click
Dim iCounter As Integer
iCounter = 0
Do While iCounter <= lstRight.ListCount - 1
If lstRight.Selected(iCounter) = True Then
)lstLeft.AddItem lstRight.List(iCounter
lstRight.RemoveItem iCounter
iCounter = iCounter - 1
End If
iCounter = iCounter + 1
Loop
End Sub

64
Selected CheckBoxes
Style
.1-CheckBox
Scroll
ScrollBars .

ComboBox
ListBox
ComboBox ComboBox ListBox
TextBox
.Style Style 0-Dropdown
Combo
ListBox 1-Simple
Combo 2-
Dropdown List
.
Scorll
ListBox Visual Basic -
ComboBox MouseDown
MouseMove !MouseUp
.Microsoft

PictureBox
PictureBox Form

PictureBox
AutoSize
- .Picture PictureBox
.

Image
Image PictureBox
Picture

65
.... DrawMode AutoRedraw HasDC Line
.... Cirlce .... Resize Paint
! Image Windowless
Control PictureBox
System Resources .PictureBox
Image
.PictureBox

ScrollBars
HScorllBar VScorllBar
.Windows Min Max
Value
.
SmallChange
LargeChange
.
Delphi
Visual Basic

PictureBox
:
)(Private Sub Form_Resize
If Me.ScaleHeight < picMain.Height Then
VScroll1.Move 0, 0, VScroll1.Width, Me.ScaleHeight - HScroll1.Height
picMain.Left = VScroll1.Width
VScroll1.Min = 0
)VScroll1.Max = -(picMain.Height - Me.ScaleHeight
VScroll1.SmallChange = 50
VScroll1.LargeChange = 500
Else
picMain.Left = 0
VScroll1.Move Me.ScaleWidth + VScroll1.Width
End If

66
If Me.ScaleWidth < picMain.Width Then
_ HScroll1.Move VScroll1.Width, Me.ScaleHeight - HScroll1.Height,
Me.ScaleWidth - VScroll1.Width
HScroll1.Min = 0
)HScroll1.Max = -(picMain.Width - Me.ScaleWidth
HScroll1.SmallChange = 50
HScroll1.LargeChange = 500
Else
HScroll1.Move 0, Me.ScaleHeight + HScroll1.Height
End If
End Sub


DirListBox DriverListBox FileListBox

Windows
-
" : !".
DriverListBox
DiskDrive :Drive
)(Private Sub Form_Load
"\Drive1.Drive = "C:
End Sub

Change
DirListBox
:DriveListBox
)(Private Sub Drive1_Change
Dir1.Path = Drive1.Drive
End Sub

67

- :A -
:
)(Private Sub Drive1_Change
On Error Resume Next
Dir1.Path = Drive1.Drive
If Err Then
Drive1.Drive = Dir1.Path
Err.Clear
End If
End Sub

FileListBox
DirListBox :
)(Private Sub Dir1_Change
File1.Path = Dir1.Path
End Sub

Path
DirListBox :FileListBox
"Dir1.Path = "C:\Windows
File1.Path = "C:\Winnt

FileListBox Pattern
:
File1.Pattern = *.EXE
File1.Pattern = *.TXT;*.DOC;*.RTF
*File1.Pattern = ABC*.

Archive Normal
ReadOnly Hidden .System ReadOnly
Hidden :

68
File1.ReadOnly = False
File1.Hidden = True

FileName .
:

ListBox ComboBox
ListCount List ListIndex.


Frame

.BorderStyle
Line
Y1 X2 X1 Y2 Top Left
Width Height
Shape 6
.
Timer Timer
Interval 0.001 .
OLE OLE
.
OLE .
:

Timer
Timer Processing
System Resources
.

69

" " :

: !
)/ ()/
()/ ( .
. .

!!!
.

70

BASIC
Visual Basic Visual Basic
BASIC High
level programming language BASIC Visual Basic
Visual Basic
.Form Designer Syntax
.Visual Basic
Visual Basic
Windows .

.

.
.



Visual Basic .
Visibility -Scope
X
:MySub1
)( Sub MySub1
Dim X As Integer
X = 20

71
End Sub
X

)( Sub MySub2
Print X
End Sub

LifeTime
X
.Sub1 Visual Basic

:
:
Dynamic Local Variables



. Dim :
Dim sName As String
Dim iAge As Integer

Option Explicit
BAS
Option Explicit
:
= sName
iAge = 99


:
= sCompanyName
Print sConpanyName 0

72
Print "
" sConpanyName
sCompanyName Bugs .

Variant Variant
.
Option Explicit
.

.
:

IDE
Option Explicit
.... .
Require Variable Declaration Editor
.Options

0
"" .Nothing
:
Static Local Variables


BAS
. Static
:Dim
Static bStaticVariable As Boolean

73
)( Static Sub Counter

Dim iCounter As Integer
Dim iCounter2 As Integer

End Sub




:
)( Sub PrintData
Static bIsPrinting As Boolean
If bIsPrinting Then
Exit Sub
Else
bIsPrinting = True
End If

End Sub
)( Sub Counter
Static iCounter As Integer
iCounter = iCounter + 1
End Sub

Static
.
:

Module BAS Form .... Class

74
.
.

Dim :Private
Dim sName As String
Dim iAge As Integer
)( Sub SetData
= sName
iAge = 99
End Sub
)( Sub PrintData
Print sName
Print iAge
End Sub


Public :
BAS
Public iNumberOfUsers As Integer
Form1
Public sCurrentUser As String
Form2
)(Private Sub Form_Load
If iNumberOfUsers <= 0 Then
Exit Sub
Else
Me.Caption = Form1.sCurrentUser
End If
End Sub

75
:

Global
Visual Basic
Public
BAS.



BAS
.


-
.
Byte
String
2.
:Visual Basic
:Byte
] [255 0
1 . Byte
VB4 16bit VB4
Byte API

Byte UNICODE
2 1 .ASCII
Strings Byte
API
.Byte
:Integer

76
] [32,767 32,768-
Integer 2 . API
Integer .UNICODE
API
Long
Integer
.API
Integer %50 .
:Long
Long ]-
[2,147,483,647 2,147,483,648 4

Integer
Overflow
Integer
:32,767
Dim iFileSize As Integer
32,676
)iFileSize = FileLen (C:\MyFile.DAT

:Boolean
Boolean Integer
False 0 True 1-
Boolean Integer 2
1 15 . 2
Boolean
.

77
:Single
Single
1.401298e-45 3.402823e38 -3.402823e38
-1.401298e-45 4.
Visual Basic Single Double

Math Coprocessor

Floating Point
Single Double Double
Single OverFlow
. Single
Double
CurrentX Circle Line ScaleWidth ScaleHeight
.... Single Double
Visual Basic .Single
:Double
Double
4.9406564581247e-324 1.79769313486232e308
-4.9406564581247e-324 -1.79769313486232e308
8.
Visual Basic Double

.Double
:Currency
Currency Fixed-
Point ]922,337,203,685,477.5808-
[922,337,203,685,477.5808 8 .
.... Round Fix
Double Single
Currency

78
Double Single
.
:Decimal
Decimal
MSDN .
Decimal Dim X As Decimal
- Variant 16 - :
Dim X As Variant
)X = CDec (Text1.Text) * CDec (Text2.Text

Variant
" "Varaint.
:Date
1 100 31
9999 00:00:00
23:59:59 8
Date Double
37257.5
1 .2002

:
Dim dDateVar As Date
dDateVar = Now

)Print Int(dDateVar

))Print CDate(dDateVar - Int(dDateVar

Print dDateVar + 7
30

79
Print dDateVar - 30
6
Print dDateVar - 0.75



VB VBA
.

:String
BASIC !String
C

3 6
Visual Basic String
.
VB4 32 - Strings
UNICODE .ASCII
Visual Basic Fixed-length
.Variable-Length

:
Dim FixedStr As String * 12
= sFixedStr

FixedStr 12
24 UNICODE 2
.
COM VB VBA API

" "
Public
64

80

Visual Basic
.....
:

COM Component Object Model


OLE Windows

" "COM .

Variable-Length
10 +

Visual Basic
2 .
:Object
Object
:Object
Dim X As Object
Dim Y As Form
Dim Z As Text

-Object
" "
:Set
Set X = New MyClass
Set Y = Form1
Set Z = Text1
= Z
= Z.Text

81
:Variant
Variant VB3
VB4 COM
.... Long Date String :.
Variant 16
2 7
Decimal 8 15
.
Variant

Visual Basic
:
Dim X As Variant
Dim Y As Variant
Dim Z As Variant
Integer
Long
Long
Double
Double

X = 2000
)Y = CLng(2000
Z=X+Y
)X = CDbl(2.5
Z=X+Y


+ Variant

& Visual
Basic
Type Mismatch :
Dim X As Variant
Dim Y As Variant
Dim Z As Variant
X = 20

82

Z = 40
Z = 2020

"Y = "20
Z=X+Y
"X = "20
Z=X+Y
Print Z
X = 20
"Y = "abcd
Z=X+Y

Variant

.Decimal
Variant
:VarType

2 Integer
20 String

Dim X As Variant
X = 20
)Print VarType(X
"X = "20
Print X

Variant Empty
:IsEmpty
Dim X As Variant
True
False
True

)Print IsEmpty(X
"X = "20
)Print IsEmpty(X
X = Empty
)Print IsEmpty(X

Null Empty Null


:DataBases

83
Dim X As Variant
True
1 Null

X = Null
)Print IsNull(X
)Print VarType(X

Variant Objects
Set
VarType
IsObject :
Dim X As Variant
True
Text1.Text

Set X = Text1
)Print IsObject(X
"" = X.Text

Variant
" " UDT
Variant Public
Module Public
.Classes


Decimal &H Hexadecimal
&O :
15
Print 15
Print &HF
Print &O17


Hexadecimal F E .... 2 1 0 Octal

84
Visual Basic Integer &
Long
:

-4096
61440
-4096
61440


&HF000 = 61440
Print &HF000
&Print &HF000

&O170000 = 61440
Print &O170000
&Print &O170000

Strings
" " "
:
:

123456

" " Print


"Print "123""456
"""" Print




Compiling EXE.
:Const
Const PI = 3.14
Print PI

85
Const PI As Double = 3.14
= Const PROGRAMMER_NAME As String
&Const SPECIAL_VALUE As Long = &H32FE


- Integer
:Type Mismatch
Const PI As Integer = 3.14 3
Const PI As Integer = abc

Private

.BAS
:Public
Public Const PI As Double = 3.14

Enum

.Enumeration Enum

:
Private Enum enmDay
Saturday
SunDay
MonDay

86
TuesDay
Wednessday
Thursday
Friday
End Enum

:
Dim X As enmDay
Dim Y As enmDay
X = Saturday
Y=X

:
)Private Sub MySub(TheDay As enmDay
If TheDay = Friday Then
"" MsgBox
Exit Sub
End If
End Sub

Enum
Long :
Dim X As enmDay
X = Saturday
Print X
X=X+1
Print X

0
:

87
Private Enum enmDay
Saturday = 20
SunDay = 30
MonDay
TuesDay
Wednessday
Thursday
Friday
End Enum

.1

UDT
User Defined
Types
: Type
Private Type typPerson
sName As String
bSingle As Boolean
iAge As Integer
End Type

:
Dim Turki As typPerson
Dim Ali As typPerson
Turki.sName = ""
Turki.iAge = 99
Turki.bSingle = True
Ali.sName = ""
Ali.iAge = 35
Ali.bSingle = False

88
:
Ali = Turki
Print Ali.sName

LenB :
)Print LenB (Turki

:
Private Type typAdress
sCountrey As String
sCity As String
End Type
Private Type typPerson
sName As String
bSingle As Boolean
iAge As Integer
Address As typAdress
End Type

:
Dim Turki As typPerson
" " = Turki.sName
Turki.iAge = 99
Turki.bSingle = True
"" = Turki.Address.sCity
" " = Turki.Address.sCountrey


Public Classes
Public BAS Visual Basic

89

Public
Parameters:
)Public Sub MySub(P As typPerson
)Private Sub MySub(P As typPerson
)Freind Sub MySub(P As typPerson

Classes
Public Instancing 1-
.Private

Visual Basic Arrays


60:
100

Dim OneDim (99) As Intger


Dim TwoDim (4, 9) As Integer
Dim ThreeDim (2, 2, 2) As Integer

Dim OneDArray(0 To 10) As String


Dim TwoDArray(0 To 10, 0 To 10) As Long
Dim OneDArray(15 To 22) As String


Array Index Option
Base 1 :
OneDim (0) = 100
OneDim (1) = 200
))TwoDim (0, 0) = (100, OneDim (0) + OneDim (1

90
:


Visual Basic

Option Base 1
.

LBound UBound
:
Dim lCounter As Long
)For lCounter = LBound (OneDim) To UBound (OneDim
)Print OneDim (lCounter
Next

UBound
:LBound
4
4
9

)Print UBound (TwoDim


)Print UBound (TwoDim, 1
)Print UBound (TwoDim, 2

TwoDim OneDim ThreeDim



Dynamic Arrays
:
Dim DynamicArray () As String

ReDim
:
)ReDim DynamicArray (2
= )DynamicArray (0

91
= )DynamicArray (1
= )DynamicArray (2

ReDim
:
)ReDim DynamicArray (4
= )DynamicArray (3
! = )DynamicArray (4
"!"

)Print DynamicArray (4
)Print DynamicArray (2


Preserve :
)ReDim Preserve DynamicArray (4
= )DynamicArray (3
! = )DynamicArray (4
"!"
""

)Print DynamicArray (4
)Print DynamicArray (2

Preserve
:
Dim OneDim () As Integer
Dim TwoDim () As Integer
)ReDim OneDim (4
)ReDim TwoDim (2, 2

:Preserve

92

)ReDim Preserve OneDim (3, 3
)ReDim Preserve TwoDim (1

)ReDim OneDim (3, 3
)ReDim TwoDim (1

VB6

:
Dim MyArray (20) As Integer
Dim YourArray () As Integer
MyArray (0) = 10
MyArray (1) = 20

)( YourArray () = MyArray
Print YourArray (0) = 10


:Erase
Erase OneDim

Variant :
Variant
:
Dim Cities(2) As String
Dim vCities As Variant

"" = )Cities(0
"" = )Cities(1
"" = )Cities(2
vCities = Cities
)Print vCities(1

93
:Array
Dim vCities As Variant
)"" "," ","(vCities = Array
)Print vCities(0

Variant
Variable-Dimension Arrays

Variant
:
Dim VarDim(2) As Variant
" " = )VarDim(0
)" ", "2 VarDim(1) = Array("1
)" ", "3 ", "2 VarDim(2) = Array("1
)Print VarDim(0
)Print VarDim(1)(0), VarDim(1)(1
)Print VarDim(2)(0), VarDim(2)(1), VarDim(2)(2


. Collections
.
.
:
Collections VBA
:

94
.
.
.

.
String Integer
.
Key .
!

100! .

!

.
:

-:Collection -
Dim MyCol As New Collection

Add .
Key
:

95
MyCol.Add "amazon.com", "shopping"
MyCol.Add "hotmail.com", "mail"
MyCol.Add "yahoo.com", "Search"

- - Item
:
Print MyCol.Item(1) ' amazon.com
Print MyCol.Item("mail") ' hotmail.com
Print MyCol("Search") ' yahoo.com

:Remove
MyCol.Remove 1
MyCol.Remove "mail"

:
Set MyCol = Nothing

: !

MyCol.Add "amazon.com", "shopping"

Set MyCol = New Collection
MyCol.Add "amazon.com", " shopping"

:Count
Print MyCol.Count

96

Visual Basic Subs Functions



:

Function GetUserName () As String
= GetUserName
End Sub
UDT
Function GetPersonData () As typPerson
= GetPersonData.sName
GetPersonData.iAge = 99
End Function

:
Function OddNumbers() As String
Dim iCounter As Integer
= OddNumbers
For iCounter = 0 To 9
If iCounter Mod 2 <> 0 Then
OddNumbers = OddNumbers & iCounter
End If
Next
End Function


Exit Sub Exit Function
Recursion Exit Function
:

97
Function Factorial(iNum As Integer) As Long
If iNum = 1 Then
Factorial = 1
Exit Function
Else
)Factorial = iNum * Factorial(iNum - 1
End If
End Function

Public
:
BAS
)( Sub MySub1

End Sub
Public

Form1
)( Public Sub MySub2

End Sub
Form2
)(Private Sub Form_Load
MySub1
Form1.MySub2
End Sub

Private
:
Form1
)( Private Sub MySub

End Sub

98

Form1

Form2
)(Private Sub Form_Load
Form1.MySub
End Sub

Friend Public
Standard EXE
ActiveX Public
COM Friend
.

Sub's Functions .Parameters



. Subs Functions
Integer String
.... UDT .Classes
.Arrays

.
.
ByVal
.
. Reference

:
)(Sub Start

Dim X As Integer
' X=0
Print X
MySub X
' X=5

99
Print X
End Sub
)Sub MySub (X As Integer
X=5
End Sub

MySub
Integer .
:
)Sub Swap (X As Variant, Y As Variant


Dim vTemp As Variant
vTemp = X : X = Y : Y = vTemp
End Sub

Strings
Visual Basic
.
:ByVal
)(Sub Start

Dim X As Integer, Y As Integer
' X = 0, Y = 0
Print X, Y
MySub X, Y
' X = 3, Y = 0
Print X, Y
End Sub
)Sub MySub (X As Integer, ByVal Y As Integer
X=5

100
Y = 10
End Sub


.... Double Integer String
Controls
VB VBA .... Screen Printer App UDT
:
:
Standard EXE
ActiveX
.... ActiveX OCX EXE
Private Friend
Public
COM " COM
."1
:UDT
UDT Type
:
Private ..
.
Public BAS
.Public
Class ActiveX
COM Instancing .1-Private

101


Optional
.Unlimited Parameters
:

.

.
.Optional
IsMissing ! IsMissing
Variant:
)(Sub Start

' MyFunction = -1
)(Print MyFunction
' MyFunction = 4
)Print MyFunction (2
End Sub
Function MyFunction (Optional X As Variant) As Integer
If IsMissing(X) Then

MyFunction = -1
Else

MyFunction = X ^ 2
End If
End Function

Variant
IsMissing .

:

102
)(Sub Start

' MyFunction = -1
)(Print MyFunction
' MyFunction = 4
)Print MyFunction (2
End Sub
Function MyFunction (Optional X As Integer = -1) As Integer
If X = -1 Then

MyFunction = -1
Else

MyFunction = X ^ 2
End If
End Function

Optional
- .

:


ParamArray .Variant
:
Function Sum (ParamArray args() As Variant) As Long
Dim iCounter As Integer
)For iCounter = 0 To Ubound(args
)Sum = Sum + args(iCounter
Next iCounter
End Function

103
'Sum = 10
)Print Sum (5, 5
'Sum = 100
)Print Sum (20, 20, 20, 20, 20
'Sum = 1000
)Print Sum (250, 250, 250, 250

%90
If Select For Next Do Loop
Branch Statements
.Looping Statements

IF
If Visual Basic
. If
- :

If X > 0 Then Y = 0
If X > 0 Then Y = 0 Else Y = X
If X > 0 Then X = 0 : Y = 0 Else Y = X

If X > 0 Then
Y=0
End If
If M > 0 Then
T=1
Else
T = -1
End If
If M > 0 Then

104
T=1
ElseIf M < 0 Then
T = -1
Else
T=0
End If

:
If True
If Then :
If Value = True Then
End If
If x <> 0 Then
End If

If
Value .
:
If Value Then
End If

Visual Basic
True False .If
:
If x Then
End If

105

.
.
:
x=3
y=4
If x <> 0 And y <> 0 Then
If x And y Then


!
x y 0011 0100
And Or
.

Select
:Select

=
=
=
=

Select Case iDay


Case 1
sDay
Case 2
sDay

Case 7
sDay
Case Else
sDay
End Select

Case
:

106
Select Case iAge
Case Is <= 0
sDesc =
Case 1 To 11
sDesc =
Case 15 To 20
sDesc =
Case 21 To 50
sDesc =
Case Is >= 51
sDesc =
End Select

:
Select Case sLetter
Case A To B, a To b
sLetter =
Case 0 To 9
sLetter =
Case ., :, , ;, ?
sLetter =
Case
sLetter =
End Select

:
Select Case True
Case x > 0, Y < 0

If (X > 0) Or (Y < 0)
End Select
Select Case False
Case x > 0, Y < 0

107
) ) If ( Not (X > 0) ) Or ( Not (Y < 0
End Select


:For Next
Dim iCounter As Integer
For iCounter = 2 To 4
Print iCounter
Next

:
Dim iCounter As Integer
For iCounter = 1 To 3
Print iCounter
Next
4 Print iCounter 3

:Step
Dim iCounter As Integer
For iCounter = 10 To 0 Step -1
Print iCounter
Next

Nested Loops
:
Dim A As Integer
Dim b As Integer

108
For A = 1 To 5
For b = A To 5
Print A, "x", b, "=", A * b
Next
Next

:Exit For
Dim iCounter As Integer
For iCounter = 0 To 100
If MsgBox("" , vbYesNo ) = vbYes Then
Exit For
End If

Next

:Collections For Each


Dim ctrl As Control

For Each ctrl In Controls
ctrl.Left = 0
Next

:Variant

Dim X(100) As Integer


Dim Y As Variant


For Each Y In X
Print Y
Next

109
Do Loop For Next
While :Until
", vbYesNo ) = vbYes "(Do While MsgBox

Loop
", vbYesNo ) = vbNo "(Do Until MsgBox

Loop

True
While False
.Until
:
Do

", vbYesNo ) = vbNo "(Loop While MsgBox


Do

", vbYesNo ) = vbYes "(Loop Until MsgBox

If Select
:Exit Do
Do
", vbYesNo ) = vbYes Then "(If MsgBox
Exit Do
End If

Loop

110
For Next :Do Loop
For Next Do Loop
For Next
:
A=5
For iCounter = 1 To A

Next
iCounter = 1
Do

iCounter = iCounter + 1
Loop Until iCounter > A

A For
Next 5 A
Do
.Loop

Optimization

System Resources .
Visual Basic
Compile Project
.Properties

P-Code Native Code


- -F5 Visual Basic
. Visual Basic
P-Code .

111
Native Code Machine Language
. P-Code
.Visual Basic
P-Code
.Native Code P-Code Native Code
Machine Language Visual Basic
. Native Code
Visual Basic Compile
:Project Properties
:Optimize for Fast Code

. EXE
:Optimize for Small Code

.
:

:No Optimization
Optimization
.
:Favor Pentium Pro
Pentium Pro
.

112
:Create Symbolic Debug Info

Debug
.Microsoft Visual C .

Advanced Optimization

Visual Basic
:Advanced Optimization

:Assume No Aliasing

. -
:ByRef
Dim X
)Sub MySub ( Y As Integer
Y=4
End Sub
)(Sub AliasingSub

MySub X
End Sub

:Remove Array Bound Checks


Array Index
.
:Remove Integer Overflow Checks

.
:Remove Floating Point Error Checks
.Floating Point

113
:Allow Unrounded Floating Point Operations
.
:Remove Safe Pentium FDIV Checks

Pentium .FDIV
Optimization

System Resources .
Visual Basic
Compile .Project Properties
-
!

114

VB VBA
Visual Basic VB VBA


Visual Basic
Optimization
.Visual Basic

MSDN
.

Visual Basic Operators


.... Long Integer Byte
.


Visual Basic * - + /

Integer Long Single Double /
Double
\ Integer Byte
Long :/

115
Dim X As Long, Y As Long, Z As Long
Z=X/Y
Z = X \ Y

^ Double

:
Dim X As Long, Y As Long,
Y=X^3
Y=X*X*X

MOD Long
Double Single
:Long
Function ModEx (dN As Double, dD As Double) As Double
ModEx = dN Int(dN / dD) * dD
End Function

Visual Basic =
< >= > <= >< . =
= Visual Basic
:
Dim X As Integer, Y As Integer
X = Y = 10

=
.
:


C ==
=.

116
XOR AND NOT
Bits
.Binary
:

And Or And
Or Or
And :
Print True Or False And False

False
True And .Or
:
Print (True Or False) And False

Not And
And :
Print Not True And False

Not True False And


False And .False
And
:
)Print Not (True And False

.True

117


Visual Basic Abs
Sqr Exp Sgn 1
1-
.
Log
:
Function LogEx (dN As Double, dBase As Double ) As Double
) LogEx = Log ( dN ) / Log ( dBase
End Function

Sqr
:
Function NthSqr (iNum As Integer, iRoot As Integer) As Double
)NthSqr = iNum ^ (1 / iRoot
End Function
'
' 8
Print NthSqr( 8, 3) ' 2

Tan Cos Sin Atn


Sec
.... Cosec
:
Function Sec (X As Double) As Double
)Sec(X) = 1 / Cos(X
End Function

118


Format

.
Format - - :
) , ( Format

.
.
General Number Currency
:MSDN
1234567
)"Print Format(1234567, "General Number
1,234,567.00. .
)Print Format(1234567, "Currency
1,234,567
)Print Format(1234567, "Standard

.
.... 0 % # :MSDN
' 1, 234.57
)"Print Format(1234.567, "#,##.00
' 23.4%
)"Print Format(0.234, "#.#%
' 020.0
)"Print Format(20, "00#.00


Int Fix
:

119

Int(1.2) ' 1
Int(-1.2) ' -2
Fix(1.2) ' 1
Fix(-1.2) ' -1

Print
Print
Print
Print

Round VB6
:
Print Round(2.12567, 2) ' 2.13

Hexadecimal Octal
Hex Oct :
Print Hex$(100) ' 64
Print Oct$(100) ' 144

Binary Bin:
Public Function Bin(iNum As Integer) As String
Dim iCounter As Integer
Do
If (iNum And 2 ^ iCounter) = 2 ^ iCounter Then
Bin = "1" & Bin
Else
Bin = "0" & Bin
End If
iCounter = iCounter + 1
Loop Until 2 ^ iCounter > iNum
End Function

Rnd 1
:
) + 1) * Rnd + (( Int

120
] [4 2- :
)Print Int(7 * Rnd + -2

Val
CInt Integer CLng
CDbl Long .... Double.

VB VBA
.Strings
Find and Replace
.


& Combine Operator :
Dim sMyName As String
= sMyName
& sMyName = sMyName
Print sMyName

" "+
"&"

Type Mismatch
:
2030
50

Print 20 + 30
Print 20 + 30
Print X + 100

121
< .... = <>
ASCII
:UNICODE
True
False
False
False
True
False

""Turki" > "TURKI


""Turki" < "TURKI
""Turki" = "TURKI
"" > ""
"" < ""
"" = ""

Print
Print
Print
Print
Print
Print

Visual Basic

Option Compare Text
.


Like #
* :
Dim sMyString As String
= sMyString
If sMyString Like A???? Then
A1234 Abcde
If sMyString Like A* Then
Aabce1234 Ab
A1234 If sMyString Like A#### Then A0000

] [:
Dim sMyString As String
= sMyString
B1234 If sMyString Like [AB]### Then A1234

122
BY If sMyString Like [AB][XY] Then AX
D3 If sMyString Like [A-D]# Then C9

!:
Dim sMyString As String
= sMyString
Z1234 A1234

If sMyString Like [!0-9]### Then

InStr
:
Dim lPosition As Long
Dim lStartPoint As Long
lStartPoint = 1
)"" lPosition = InStr (lStartPoint, Text1.Text,
If lPosition > 0 Then
Text1.SelStart = lPosition - 1
Text1.SelLength = 4
End If

InStrRev
- .
Replace
. ""
" " :
)" " "," Text1.Text = Replace(Text1.Text,

123


Format
@
& :
)"@ @ @ @" Print Format("ABCD",
A B C D
)"&&& @" Print Format("ABCD",
A BCD
Print Format("9661234567", "&&&-&-@@@@@@") 966-1-234567

Left$
Right$ :Mid$
Dim sMyString As String
sMyString = ABCDEFGHIJKLMNOPQRSTUVWXYZ
)Print Left$ ( sMyString, 5
ABCDE
)Print Right$ ( sMyString, 5
VWXYZ
)Print Mid$ ( sMyString, 20, 5
TUVWX
)Print Mid$ ( sMyString, 20
TUVWXYZ

Right Left
. Right$ ""
.. .

ArRight :ArLeft
Function ArLeft(sString As String, lLength As Long) As String
)ArLeft = Right$(sString, lLength
End Function
Function ArRight(sString As String, lLength As Long) As String
)ArRight = Left$(sString, lLength
End Function

124
)(Private Sub Form_Click
'
' )", 4 "(Print ArRight$
' )", 7 "(Print ArLeft$
End Sub

Mid$ Mid$ Statement


:
Dim sMyString As String
"sMyString = "abcde
"Mid$(sMyString, 2, 3) = "BCD
Print sMyString
aBCDe


Len
:
If sMyString = Then
If Len(sMyString) = 0 Then

RTrim$ LTrim$
:Trim$
12345
12345
12345

sMyString = 12345
)Print RTrim$ (sMyString
)Print LTrim$ (sMyString
)Print Trim$ (sMyString

Asc ASCII AscW


UNICODE Chr$ ChrW$ :
202
1578

)""(Print Asc
)""(Print AscW
)Print Chr$(202

125

)Print ChrW$(1578

UCase$ LCase$
.
Turki :TURKI
If Text1.Text = TURKI Then

If UCase$( Text1.Text ) = TURKI Then
If LCase$( Text1.Text ) = turki Then

UCase$ LCase$

vbProperCase :StrConv
I Like Visual Basic
i like visual basic
I LIKE VISUAL BASIC

"sMyString = "I like Visual Basic


)Print StrConv(sMyString, vbProperCase
)Print StrConv(sMyString, vbLowerCase
)Print StrConv(sMyString, vbUpperCase

StrConv ASCII UNICODE


vbUnicode UNICODE ASCII .vbFromUnicode
:


String .Variant
-
$
Visual Basic .

Split
:
Dim X() As String
Dim iCounter As Integer
)X = Split(Text1.Text

126

)"*" X = Split(Text1.Text,
)For iCounter = 0 To UBound(X
)Print X(iCounter
Next

Join :
)sFromArrayToString = Join (X
)* sFromArrayToString = Join (X,

Str$ CStr
.

Visual Basic
Date
.

Date
Date # :#
Dim MyDate As Date
MyDate = #1/20/2001#
Print MyDate
MyDate = #2:30:00 AM#
Print MyDate
MyDate = #1/20/2001 2:30:00 AM#
Print MyDate

127

Calendar VBA
:
Dim MyDate As Date
MyDate = #1/20/2001 2:30:00 AM#
' VBA.Calendar = vbCalHijri
Print MyDate
' VBA.Calendar = vbCalGreg
Print MyDate


:
Dim MyDate As Date

VBA.Calendar = vbCalHijri
MyDate = #1/16/1421#
Print MyDate

Date Time
:
Print Date
Print Time

Date Time Statement


:
Date = #1/20/2001#
Time = #12:00:00 AM#

Now :
Print Now

128
Timer

:
)Sub Wait ( iSeconds As Integer
Dim sStartTime As Single
sStartTime = Timer
Do: DoEvents : Loop Until Timer sStartTime >= iSeconds
End Sub

Timer 00:00:00
23:59:59 Wait
Timer .

" ":
)Sub Wait ( iSeconds As Integer
!Const NUMOFSEC As Single = 24 * 60 * 60
Dim sStartTime As Single
sStartTime = Timer
Do : DoEvents
Loop Until (Timer + NUMOFSEC sStartTime) Mod NUMOFSEC >= iSeconds
End Sub

# #
DateSerial
Calendar :VBA
Dim MyDate As Date
VBA.Calendar = vbCalHijri
27 MyDate = DateSerial(1422, 10, 27) 1422
Print MyDate
VBA.Calendar = vbCalGreg
11 Print MyDate 2002

129
.TimeSerial
DateValue TimeValue
:
)Print DateValue(Now + 2
)Print TimeValue(Now

DatePart
Minute Hour Year Month Day Second

:
)Print Month (Date
)Print Hour (#1:20:00 AM#

:

.
" "Date -

:
12
Print Now + 2 + #12:00#

DateAdd
DateDiff .
DateAdd :
) , ,( DateAdd

" "yyyy " "m ""d


....
:

130
)Print DateAdd ("m", 3, Now

DateDiff
:
Print DateDiff("d", #12/20/2000#, #2/18/2001#) 60


Format
:
Dim sMyDate As Date
sMyDate = Now
)"Format$(sMyDate, "General Date
)"Format$(sMyDate, "Long Date
)"Format$(sMyDate, "Long Time
)"Format$(sMyDate, "HH:MM -> MMMM DD, YYYY

Print
Print
Print
Print

VB6 FormatDateTime
MonthName :
VBA.Calendar = vbCalHijri
)Print MonthName(1
VBA.Calendar = vbCalGreg
)Print MonthName(1

VB6
Visual
.Basic
....

131
Folders
.


Name As FileCopy
Kill :

Name C:\MyFile.EXT As C:\MyFile.DAT

Name C:\MyFile.EXT As D:\MyFile.EXT

FileCopy C:\MyFile.EXT As D:\MyFile.EXT

FileCopy C:\MyFile.EXT As C:\MyFile2.EXT

Kill C:\MyFile.EXT

Kill *.TMP

GetAttr File Attributes SetAttr


:
Dim sFile As String
sFile = C:\File.EXT
If GetAttr(sFile) And vbHidden Then
If GetAttr(sFile) And vbReadOnly Then
If GetAttr(sFile) And vbArchive Then

SetAttr sFile, vbHidden



SetAttr sFile, vbArchive + vbReadOnly

SetAttr sFile, GetAttr(sFile) Xor vbReadOnly

FileLen FileDateTime
:

132
) Print FileLen ( sFile
) Print FileDateTime ( sFile

FileLen

-
.


CurDir$
:

D:

Print CurDir$
)Print CurDir$ (d

ChDrive ChDir
:
ChDrive D:
ChDir D:\MsgFolder

ChDir
ChDrive

CurDir$ .


MS-DOS .

:
ChDrive C:
ChDir C:\UnwantedFolder
*Kill *.

133

C:\UnwantedFolder
Windows .


Dir .
: //

: C:\WinNT
Dim sFileName As String

)sFileName = Dir$ (C:\Winnt\*.EXE

)Do While Len (sFileName
List1.AddItem sFileName
sFileName = Dir$
Loop



VB VBA
.
Open :
As # Lock For Open



FreeFile
.
Lock Read

134
Lock Write .Lock Read Write
:
:Sequential Access
.
Input
OutPut Append :
Open MyFile.TXT For Input As #1
Open MyFile2.TXT For OutPut As #2
Open MyFile3.TXT For Append As #3

- -Input
Line Input :EOF
Dim sLine As String
Open MyFile.TXT For Input As #1
)Do While Not EOF(1
Line Input #1, sLine
Text1.Text = Text1.Text & vbNewLine & sLine
Loop


Input$ LOF :
Dim sFileData As String
Open "C:\MyFile.TXT" For Input As #1
)sFileData = Input$ (LOF(1), 1
Text1.Text = sFileData

- OutPut
-Append :Print #
Open C:\MyFile.TXT For Append As #1

135
Print #1, Text1.Text

Close
:
1
Close #1

Close

:Binary Access
.
Binary :
Open "C:\MyFile.DAT" For Binary As #1
Open "D:\YouFile.DAT" For Binary As #2

.
.
1
. LOF
:
)Print LOF (1
)Print LOF (2

" "
. Get Put .
:
Dim X As Long
Get #1, 1, X
Print X

136
Get #1, , X 5
Print X


.
4 = 4
.Long
:
Dim lCounter As Long
Dim X As Long
)For lCounter = 1 To LOF(1
Get #1, , X
Put #2, , X
Next

:Seek

Seek #1, 1
)Seek #2, LOF(2

Strings
Visual Basic .
.Fixed Length String
100 :
Dim Y As String * 100
Get #1, , Y


Visual Basic 100
:
Dim Y As String

137

)"*" Y = String (100,


Get #1, , Y

:
Put #1, ,

String
.
%50 - Byte
:String
Dim MyArray(1000) As Byte
Open "MyFile.DAT" For Binary As #1
'
Put #1, 1, MyArray
'
Get #1, 1, MyArray

:Random Access
.
Random
:
Open "C:\MyData.DAT" For Random As #1 Len = 200

Put Get

.Len

138

: UDT
Private Type typRCD
sName As String * 20
iAge As Integer
End Type
Dim Record As typRCD
Open "C:\MyData.DAT" For Random As #1 Len = Len(Record)
Record.sName = ""
Record.iAge = 99
Put #1, 1, Record
Record.sName = ""
Record.iAge = 20
Put #1, , Record

:
Dim Record As typRCD
Get #1, 1, Record
Do While Not EOF(1)
Print Record.sName
Print Record.iAge
Get #1, , Record
Loop

VBA VB
.

139

App
App .

.
EXEName EXE Path
:
Open App.Path & \ & App.EXEName & .EXE For Binary As #1

"\" Path
Path

Boot Directory "\"
Path :
\App.Path = C:

App.Path = C:\MyProgram


Path:
Function PathEx() As String
If Right(App.Path, 1) = "\" Then
PathEx = App.Path
Else
"\" & PathEx = App.Path
End If
End Function
Open PathEx & App.EXEName & .EXE For Binary As #1

PrevInstance

:

140
If App.PrevInstance Then
MsgBox
End
End If



.
TaskVisible
-Task List

] [Ctrl+Alt+Del ] [Ctrl+Shift+ESC :
App.TaskVisible = False

Title Task
List Project
Name Project Properties
.
App
.... Minor Major
.... Trademarks LegalCopyRight .

Clipboard
Windows
Clipboard
.Windows Visual Basic
.Clipboard
:SetText
Clipboard.Clear
Clipboard.SetText Text1.Text, vbCFText

141
:

Clear

.

RTF :vbCFRTF
Clipboard.Clear
Clipboard.SetText RichTextBox1.Text, vbCFRTF

SetData :
Clipboard.Clear
Clipboard.SetData Picture1.Picture

GetText
GetFormat
:
If Clipboard.GetFormat (vbCFText) Then
)Text1.SelText = Clipboard.GetText (vbCFText
ElseIf Clipboard.GetFormat (vbCFRTF) Then
)RichTextBox1.SelRTF = Clipboard.GetText (vbCFRTF
End If

GetData :
If Clipboard.GetFormat(vbCFBitmap) Then
)Set Picture1.Picture = Clipboard.GetData(vbCFBitmap
End if

PictureBox
vbCFBitmap
:
Dim picFormat As Variant

142
)For Each picFormat In Array(vbCFBitmap, vbCFMetafile, vbCFDIB, vbCFPalette
If Clipboard.GetFormat(picFormat) Then
)Set Picture1.Picture = Clipboard.GetData(picFormat
Exit For
End If
Next

Screen

FontCount
Font
:
Dim iCounter As Integer
For iCounter = 0 To Screen.FontCount - 1
)List1.AddItem Screen.Fonts(iCounter
Next

ActiveForm
ActiveControl
:
= Screen.ActiveForm.Caption

Height Width
Resolution:
)Print "Width = " & ScaleX(Screen.Width, vbTwips, vbPixels
)Print "Height = " & ScaleY(Screen.Height, vbTwips, vbPixels

Printer
.
API Visual Basic Printer Object
.

143
Printers
.Collection .
.
.
Printers
DeviceName DeriverName Port
....:
Dim X As Integer

Printers Collection
For X = 0 To Printers.Count -1
Print Printers(X).DeviceName
Next

.
Printers
.Printer :ListBox
)(Private Sub Form_Load
Dim X As Integer

Printers Collection
For X = 0 To Printers.Count -1
List1.AddItem Printers(X).DeviceName
Next
End Sub
)(Private Sub List1_Click

)Set Printer = Printers(List1.ListIndex
End Sub

144
Printer
. ColorMode
. PrinterQuality
.
.MSDN

.... Cirlce Line Print
" ".
EndDoc
:
Printer.RightToLeft =True
Printer.FontSize = 40
Printer.Print

Print.EndDoc

KillDoc NewPage
.


.

.
! .



. .

.Bugs :

145
:Design Time Errors
Syntax Errors
. .
.
For .Next
Visual Basic
].[ENTER
X == 4 ] [ENTER
.
Auto Syntax Check Auto Syntax
Check Editor .Options
!
:Run Time Errors
.
.
Run Time Error
. :
Dim X As Byte
X = 256

.
OverFlow
Byte .255

.
:
Kill FileName.EXT


.
Dir :

146
If Dir$(FileName.EXT) Then Kill FileName.EXT


. ReadOnly
.
:ReadOnly
If Dir$(FileName.EXT) Then
If Not (GetAttr("FileName.EXT) And vbReadOnly) Then
Kill FileName.EXT
End If
End If


!
FileName.EXT Process
- -
.
.
.
:Bugs

. .
.
Beta

.



.
Visual Basic .
Microsoft MSDN

147
.
.
-
- .

Err
FileName.EXT

.Err

- - .Err

On Error Resume Next
:
On Error Resume Next
Kill FileName.EXT
If Err Then
MsgBox Err.Description
Err.Clear
End If

Err
.
Err Clear
.
If Err Then
On Error Goto X
:

148
Sub LongSub ()
On Error Goto X:

X:

MsgBox Err.Description
Err.Clear
End Sub

149

OOP
VB2 VB1 VB3 Visual Basic
Object Based Programming Language OBP
VB4 Visual Basic
Object Oriented Programming Language -OOP
Classes
Visual Basic OOP OOP
Inheritance .... OverLoading
OOP Encapsulation
Classes .Interfaces
Visual Basic OOP C++
SmallTalk JAVA OOP .
" Visual Basic - "
OOP Visual
Basic .

:
. .
.

OOP

OOP
OOP

150
Object Thing
)
(Properties ....
) (Methods ....
) (Events

.... .
Visual Basic
.... BackColor Height Left :
.... ZOrder Refresh Move : MouseMove Click
.... KeyPress .

OOP

OOP :
-

OOP



.



.


Bugs
.

OOP Visual Basic


:

151
Dim hWND As Long
)hWND = FindWindow (Form1
)ChangeCaption ( hWND, Main Menu

OOP Form1 Caption


.

OOP
Class Object
-
.

- .... 99
""
.... . Visual Basic Text1 Text2
TextBox Label2 Label1 Labe3
.Label
:OOP
:
Encapsulation OOP Putting
everything together






.

.Code Reusability


.

152
:



....
.
:
Polymorphism

Visual Basic
Move Left Click
.
.
:
Inheritance




. .


Visual Basic
.CPerson Add Class Module Project
- Class Module Open
] [F4
Class1 CPerson :
Public sName As String
Public dBirthDate As Date

153
CPerson sName
.dBirthDate CPerson
Click :
)(Private Sub Form_Click
Dim Turki As New cPerson
Dim Khaled As New cPerson
" " = Turki.sName
Turki.dBirthDate = #1/1/1900#
" " = Khaled.sName
Khaled.dBirthDate = #1/1/1979#
Print Turki.sName, Turki.dBirthDate
Print Khaled.sName, Khaled.dBirthDate
End Sub

- - Turki Khaled
CPerson sName dBirthDate
Turki
.Khaled
-
.

Classes
.


CPerson
dBirthDate
:
) Turki.iAge = CDate ( Text1.Text

154



:dBirthDate
If CDate( Text1.Text ) > Date Then
MsgBox
Else
)Turki. dBirthDate= CDate(Text1.Text
End If


dBirthDate
:
Private m_dBirthDate As Date
Public Property Get dBirthDate () As Date
dBirthDate= m_dBirthDate
End Property
)Public Property Let dBirthDate (ByVal dNewValue As Date
If dNewValue > Date Then
MsgBox
m_dBirthDate = Date
Else
m_dBirthDate= dNewValue
End If
End Property

MsgBox
-

Err.Raise .MsgBox MsgBox
.

155
:
dBirthDate Let dBirthDate
dNewValue
dBirthDate Get dBirthDate
. iAge
Private:
Public Property Get iAge() As Integer
)iAge = DateDiff("yyyy", m_dBirthDate, Date
End Property

Get iAge Let iAge


iAge Read Only
:Read Only Property

Print Turki.iAge
Turki.iAge = 80

Property Let Property


Get :Write Only Property
Private m_sPassword As String
)Public Property Let sPassword ( sNewValue As String
m_sPassword = sNewValue
End Property

Subs Functions
:Parameters
Private m_sAddress (2) As String
Public Property Get sAddress( iIndex As Integer) As String
) sAddress = m_sAddress ( iIndex
End Property

156
)Public Property Let sAddress(iIndex As Integer, sNewValue As String
m_sAddress ( iIndex ) = sNewValue
End Property

sAddress :
= )Turki.sAddress (0
= )Turki.sAddress (1
Turki.sAddress (2) = 999


Property Set :Property Let
Private m_PersonParent As CPerson
Public Property Get PersonParent( ) As CPerson
Set PersonParent = m_PersonParent
End Property
) Public Property Set PersonParent( ByVal objNewValue As CPerson
Set m_PersonParent = objNewValue
End Property

:Property Attributes
Procedure Attributes
Tools
. : Default Propertey
Object Browser
....
.CLS

.

157


Methods Subs Function
" "BASIC
. :CPerson
)Public Sub SetData(sName As String, dBirthDate As Date, sAddress As Variant
Me.sName = sName
Me.dBirthDate = dBirthDate
)Me.sAddress(0) = sAddress(0
)Me.sAddress(1) = sAddress(1
)Me.sAddress(2) = sAddress(2
End Sub

:

Turki.sName = txtName.Text
) Turki.dBirthDate = CDate ( txtBirthDate.Text
Turki.sAddress (0) = txtAddress1.Text
Turki.sAddress (1) = txtAddress2.Text
Turki.sAddress (2) = txtAddress3.Text

_ Turki.SetData txtName, CDate(txtBirthDate), Array(txtAddress1,
)txtAddress2, txtAddress3




COM .DCOM

158


VB4
Class_Initialize .Class_Terminates
Clients
.

Form Click

:
)(Private Sub Form_Click

End Sub

Sub
Parameters MouseDown .KeyPress
DataHasBeenSent
.CPerson
:Event

)Event DataHasBeenSent(objTo As CPerson, bSuccess As Boolean

!
Visual Basic
RaiseEvent
. :CPerson
Option Explicit

)Event DataHasBeenSent(objTo As CPerson, bSuccess As Boolean

)Public Sub SendData(objTo As CPerson

159

If objTo Is Nothing Then
)RaiseEvent DataHasBeenSent(objTo, False
Else
)RaiseEvent DataHasBeenSent(objTo, True
End If
End Sub


Click
:
-

WithEvents .
.
- .Public

Caller CPerson
:
Option Explicit
Dim WithEvents Caller As CPerson
)(Private Sub Form_Click
Dim Khaled As CPerson
Set Khaled = New CPerson
= Khaled.sName
Caller.SendData Khaled
End Sub
)(Private Sub Form_Load
Set Caller = New MyClass
End Sub

160

)Private Sub Caller_DataHasBeenSent(objTo As CPerson, bSuccess As Boolean


If bSuccess Then
" CPerson.sName MsgBox " :
Else
MsgBox
End If
End Sub


WithEvents
Combo Box
MyCaller
.

Caller_DataHasBeenSent
.SendData
:
WithEvents
Event Multicasting
.
" " "
" " "TextBox
-


:CNumTextBox

Public WithEvents TextControl As TextBox

Private OldText As String
Private OldSelStart As Long

161

Private Sub TextControl_GotFocus()




OldText = TextControl.Text
OldSelStart = TextControl.SelStart
End Sub
Private Sub TextControl_Change()

Static bExitNow As Boolean
If bExitNow Then Exit Sub
If Not IsNumeric(TextControl.Text) Then


bExitNow = True
TextControl.Text = OldText
bExitNow = False
TextControl.SelStart = OldSelStart
Else


OldText = TextControl.Text
OldSelStart = TextControl.SelStart
End If
End Sub
Private Sub TextControl_KeyDown(KeyCode As Integer, Shift As Integer)
OldSelStart = TextControl.SelStart
End Sub
Private Sub TextControl_KeyUp(KeyCode As Integer, Shift As Integer)
OldSelStart = TextControl.SelStart
End Sub
Private Sub TextControl_MouseUp(Button As Integer, Shift As Integer, _

162
)X As Single, Y As Single
OldSelStart = TextControl.SelStart
End Sub
)(Private Sub TextControl_Click
OldSelStart = TextControl.SelStart
End Sub

TextBox
:
Dim NumText As New CNumTextBox
Dim NumText2 As New CNumTextBox
)(Private Sub Form_Load
Text1 = 0
Text2 = 0
Set NumText.TextControl = Text1
Set NumText2.TextControl = Text2
End Sub

Text1 Text2
.Event Multicasting



.
:CFile


. CFile
:

163
Dim iFree File As Integer
iFreeFile = FreeFile
Open MyFile.TXT For Binary As #iFreeFile

! Put #1, ,

Dim sTemp As String
) sTemp = String (18,
Get #1, , sTemp

Print sTemp

Dim MyFile As New CFile


MyFile.OpenFile MyFile.TXT
MyFile.PutData
)Print MyFile.GetData (16



Close
.

CloseFile CFile
:CFile
)(Private Sub Class_Terminate
Me.CloseFile
End Sub

164
: CloseFile
Public Sub CloseFile()
If Me.iFileNum Then
Close #iFileNum
m_iFileNum = 0
End If
End Sub

CFile.CLS
lCursorLoc .
:
Public Property Get lCursorLoc() As Long
lCursorLoc = Seek(Me.iFileNum)
End Property
Public Property Let lCursorLoc(ByVal lNewValue As Long)
Seek Me.iFileNum, lNewValue
End Property

:
MyFile.lCursorLoc = 1
MyFile.lCursorLoc = MyFile.lLOF

.CFile Codes.ZIP

165




:New
:New
Instance Visual
Basic CreateObject GetObject
" "1 COM
New
:Set
Dim Turki As New CPerson
Dim Khaled As CPerson
Set Khaled = New CPerson


New Dim
- Class_Initialize !
. -
Visual Basic
New !
:Set
Set :
Set Khaled = Turki

166
Set
Turki
Khaled sName
:Set
Khaled = Turki


:
Khaled.sName = Turki.sName

:Is
:
If Khaled Is Turki Then

:
If Khaled Is Nothing Then


:
If Khaled = Turki Then

- - :
If Khaled.sName = Turki.sName Then

:TypeOf Is
:
If TypeOf Turki Is CPerson Then

167
If TypeOf MyCtrl Is TextBox Then
= MyCtrl.Text
Else
= MyCtrl.Caption
End If

:TypeName
TypeName :
CPerson
TextBox

)Print TypeName(Turki
)Print TypeName(Text1

:Nothing
Nothing:
Set Khaled = Nothing


- -
:
.
UDT ! %100
4 ) 32(
:
Dim X As New MyClass
Dim Y As New MyClass

X, Y

Set Y = X

168
Y.Value = 100
Y.Value = 100
Print Y.Value
X.Value = 200
!! Y.Value = 200
Print Y.Value

Set Y = X
- X - -Y -
X.Value = 200
Y.Value X Y ) (
X
.
Y !
.



- 4 -
. Integer Long
String
.
Instance Data
Area : VTable
Counter .Data Area
:
:VTable
Visual Basic COM
C++ VTable
- -Methods

169
. VTable
. VTable
VTable
:
Dim X As MyClass, Y As MyClass, Z As YourClass

VTable X Y Z VTable
MyClass .YourClass
:Counter
4
.
.
) (
:
Dim X As MyClass, Y As MyClass

Set X = New MyClass



Set Y = X

Set X = Nothing


Set Y = Nothing

:Data Area
Public
Static

170
. Long
8.
:
.
MyClass MyMethod1 MyMethod2
Public Value1 .Value2 :
Dim X As MyClass, Y As MyClass, Z As MyClass

Set X = New MyClass
Set Y = X
Set Z = New MyClass

X, Y
= X.Value1
= X.Value2

Z
= Z.Value1
= Z.Value2

:1-5

171

:1-5 Y X Z.
1-5
Binding -
COM .

Binding
Members
.VTable
VTable
:
Dim X As Object
If Y = True Then
Set X = New MyClass
Else
Set X = New YourClass
End
X.MyMethod

172
MyMethod X
X MyClass YourClass
Visual Basic
VTable MyMethod
.
:
:Early Binding
Compiling time
VTable .
.

Dim X As MyClass, Y As YourClass
Set X = New MyClass

COM

)Set Y = CreateObject (YourServer.YourClass

:Late Binding
VTable
VTable
. Object
Variant .

Dim X As Object, Y As Variant
Set X = New MyClass

COM
)Set Y = CreateObject (MyServer.YourClass

173


New
CreateObject GetObject

Nothing . :
:
Visual Basic
VTable . Visual Basic
Instancing Data Area

. VTable VTable
. Class_Initialize
.VTable

Visual Basic VTable
.
.
:
Visual Basic Class_Terminate

Instancing Data Area
Visual Basic VTable
End
VTable
.
.Class_Terminate

.

- -
Visual Basic Class_Terminate
.

174
- -
.
) Set X = Nothing X (
Visual Basic
!
Class_Terminate .
.


" "BASIC



Pointer
.
ByVal ByRef
ByVal
Counter
ByRef
:
) Sub MySub ( objPerson As Person

Set objPerson = Nothing


End Sub

) Sub MySub ( ByVal objPerson As Person

Set objPerson = Nothing


End Sub

175





.

.

Polymorphism
.OOP Visual Basic

.Abstract Classes
:
.Same names but different implementations

. CPerson CCar
Move
CPerson.Move : .CCar.Move


.

Select Case .

Left Name

176
TextBox
:
) CenterTextBox ( txtTextBox As TextBox
_ txtTextBox.Move ScaleWidth - txtTextBox.Width) / 2,
ScaleHeight - txtTextBox.Height) / 2
End Sub


Label :
)CenterLabel ( lblLabel As Label
_ lblLabel.Move ScaleWidth - lblLabel.Width) / 2,
ScaleHeight - lblLabel.Height) / 2
End Sub

18
!
:
) CenterControl ( ctrlControl As Control
_ ctrlControl.Move ScaleWidth - ctrlControl.Width) / 2,
ScaleHeight - ctrlControl.Height) / 2
End Sub


TextBox Control
Move . Control
Abstract Class Control
Interface
.
:
)( ITrip
:

177

Function GetCost(iDistance As Integer) As Integer



End Function

OOP
I
C .

:CCar


ITrip
Implements ITrip
Private Function ITrip_GetCost(iDistance As Integer) As Integer

ITrip
ITrip_GetCost = iDistance * 15
End Function


Implements
ComboBox
.

:CPlane


ITrip
Implements ITrip
Private Function ITrip_GetCost(iDistance As Integer) As Integer

178
ITrip
ITrip_GetCost = iDistance * 100
End Function

ITrip CCar CPlane


:
)(Private Sub Command1_Click
Dim NewTrip As ITrip
Set NewTrip = New CCar
)Print NewTrip.GetCost(50
Set NewTrip = New CPlane
)Print NewTrip.GetCost(50
End Sub


) 50 (.

Inheritance -Derived
- -Base Class
)/(
.

.
:
(1 CPerson : Name : AgeMove :
(2 CStudent : Major :ChangeCollege :
(3 CWorkman : Salary :ChangeDepartment :

179
CWorkman CStudent
.CPerson CStudent CWorkman
CPerson
:
= CStudent.Name
CStudent.Age = 25
)(CStudent.Move
= CStudent.Major
)(CStudent.ChangeCollege
= CStudent.Name
CWorkman.Age = 30
)(CWorkman.Move
CWorkman.Salary = 10,000
)(CWorkman.ChangeDepartment

CWorkman CStudent
CPerson ! CPerson

:
CPerson.Salary = 20,000

)(CPerson.ChangeCollege

) ( .
CStudent CWorkman
:
CStudent.Salary = 10,000
)(CWorkman.ChangeCollege

CPerson .

180
MyClass

.

Visual Basic
Visual Basic
.

.
CPerson :
Private m_sName As String
Private m_iAge As Integer
)(Sub Move
" " MsgBox
End Sub
Property Get iAge () As Integer
iAge = m_iAge
End Property
) Property Let iAge ( iNewValue As Integer
m_iAge = iNewValue
End Property
Property Get sName () As String
sName = m_sName
End Property
) Property Let sName ( sNewValue As String
m_sName = sNewValue
End Property

181
CPerson CStudent
:

Private m_sName As String
Private m_iAge As Integer
Property Get iAge () As Integer
iAge = m_iAge
End Property
Property Let iAge ( iNewValue As Integer )
m_iAge = iNewValue
End Property
Property Get sName () As String
sName = m_sName
End Property
Property Let sName ( sNewValue As String )
m_sName = sNewValue
End Property

Private m_sMajor As String
Property Get sMajor () As String
sName = m_sName
End Property
Property Let sMajor ( sNewValue As String )
m_sName = sNewValue
End Property

Sub Move()
MsgBox ""

182
End Sub

Sub ChangeCollege()
MsgBox ""
End Sub

:CWorkman

Private m_sName As String
Private m_iAge As Integer
Property Get iAge () As Integer
iAge = m_iAge
End Property
Property Let iAge ( iNewValue As Integer )
m_iAge = iNewValue
End Property
Property Get sName () As String
sName = m_sName
End Property
Property Let sName ( sNewValue As String )
m_sName = sNewValue
End Property

Private m_lSalary As Long
Property Get lSalary () As Long
lSalary = m_lSalary
End Property
Property Let lSalary ( lNewValue As Long )

183
m_lSalary = lNewValue
End Property

)(Sub Move
" " MsgBox
End Sub

)(Sub ChangeDepartment
" " MsgBox
End Sub

:
Dim X As New CStudent
Dim Y As New CWorkman
= X.sName
X.iAge = 25
)(X.Move
= X.sMajor
)(X.ChangeCollege
= Y.sName
Y.iAge = 30
)(Y.Move
Y.lSalary = 10,000
)(Y.ChangeDepartment

" "

Source
Code .
- COM - - .
OOP
Has a

184
.
CStudent CWorkman :

Public objPerson As New CPerson

Private m_sMajor As String
Property Get sMajor () As String
sName = m_sName
End Property
) Property Let sMajor ( sNewValue As String
m_sName = sNewValue
End Property

)(Sub ChangeCollege
" " MsgBox
End Sub


X.sName

.X.objPerson.sName

Delegation


:CStudent

Private objPerson As New CPerson

185
Property Get iAge () As Integer
iAge = objPerson.iAge
End Property
Property Let iAge ( iNewValue As Integer )
objPerson.iAge = iNewValue
End Property
Property Get sName () As String
sName = objPerson.sName
End Property
Property Let sName ( sNewValue As String )
objPerson.sName = sNewValue
End Property

Private m_sMajor As String
Property Get sMajor () As String
sName = m_sName
End Property
Property Let sMajor ( sNewValue As String )
m_sName = sNewValue
End Property

Sub Move()
objPerson.Move
End Sub

Sub ChangeCollege()
MsgBox ""
End Sub

186
Visual Basic - -
%100 !
- -Polymorphism
.


IMyInterface
CBaseClass .CDerivedClass
IMyInterface MyMethod
.BaseMethod
DerivedMethod
IMyInterface
MyMethod .BaseMethod
:
.
- -
CDerivedClass CBaseClass
CDerivedClass:
Private BaseClass As New CBaseClass

)(Sub BaseMethod
BaseClass.BaseMethod
End Sub

)(Sub DerivedMethod

End Sub

187

MyMethod IMyInterface
.CBaseClass :
)(Sub MyMethod
BaseClass.MyMethod
End Sub

!
Polymorphism BaseClass CBaseClass
IMyInterface .
:

IMyInterface :
Private BaseClass As New CBaseClass

Implements IMyInterface

)(Sub BaseMethod
BaseClass.BaseMethod
End Sub

)(Private Sub IMyInterface_MyMethod
Dim TempInf As IMyInterface
Set TempInf = BaseClass
TempInf.MyMethod
End Sub
)(Sub MyMethod
IMyInterface_MyMethod
End Sub

188


)(Sub DerivedMethod

End Sub

Subclassing
Delegation OOP

.
:
)(Sub BaseMethod
BaseClass.BaseMethod
End Sub

Function
:Parameters
Function BaseMethod (X As Long, Y As Long) As Long
)BaseMethod = BaseClass.BaseMethod (X, Y
End Sub



Arguments Returned Value
:
Function BaseMethod (X As Long, Y As Long) As Long
If X = 0 Then
BaseMethod = 0
ElseIf Y = 0 Then
)BaseMethod = BaseClass.BaseMethod (X, 1
Else
)BaseMethod = BaseClass.BaseMethod (X, Y

189
End If
End Sub

Subclassing
the base class
OOP C++ Visual
.Basic
VB
VBA Hex
F .... B A
Hex
:BAS
Function Hex(lNum As Long) As String
)Hex = VBA.Hex$(lNum
)"" Hex = Replace(Hex, "A",
)"" Hex = Replace(Hex, "B",
)"" Hex = Replace(Hex, "C",
)"" Hex = Replace(Hex, "D",
)"" Hex = Replace(Hex, "E",
)"" Hex = Replace(Hex, "F",
End Function

:
Dim lCounter As Long
For lCounter = 0 To 15
)Print Hex(lCounter
Next

190
Object Hierarchies .
.... Microsoft PowerPoint Microsoft Excel Microsoft Word
.... DirectX DAO ADO
.


.

.


OOP "
"Has a ""
.

. " " :
1 :1
1 1
CCar
CPerson objOwner
objDriver CCar :
CCar
Public objOwner As CPerson
Public objDriver As CPerson
Public sCarModel As String

191
.1-6

:1-6 .
200 MFC

. CCar CPerson
:
Dim Turki As New CPerson
Dim Abbas As New CPerson
Dim BMW As New CCar
= Turki.sName
= Abbas.sName

BMW.sCarModel = BMW - 7
Set BMW.objOwner = Turki
Set BMW.objDriver = Abbas

objOwner objDriver
CCar :

192
CCar
)Public Sub PrintRelatedPeople ( frmForm As Form
& Me.sCarModelfrmForm.Print :
& Me.objOwnerfrmForm.Print :
& Me. objDriverfrmForm.Print :
End Sub

OOP
.
1 :

1 .
CCar
objOwner objDriver
!
objDriver :
CCar
Private m_objDrivers (5) As CPerson
Public Property Get objDriver( iDriverNum As Integer ) As CPerson
) Set objDriver = m_objDrivers ( iDriverNum
End Property
)Public Property Set objDriver( iDriverNum As Integer, ByVal objNewValue As CPerson
Set m_objDrivers ( iDriverNum ) = objNewValue
End Property

:
BMW.objOwner = Turki
BMW.objDriver (0) = Abbas
BMW.objDriver (1) = Ahmed
BMW.objDriver (2) = Ali

Set
Set
Set
Set

193

" 1 " Array based 1


to many relationship - " 1
" Array based 1 to many relationship
objDriver Collection :
CCar
Public objDrivers As New Collection

objDriver:
BMW.objDrivers.Add Turki
BMW.objDrivers.Add Ali

objDriver :For Each


Dim objDriver As CPerson
For Each objDriver In BMW.objDrivers
Print objDriver.sName
Next


)( objDriver
:
Dim BMW As New CCar
Dim Mercury As New CCar

BMW.objDrivers.Add Mercuty

194
CPersons Collection Class

Visual Basic COM
.

Collection Classes


" " Collection Class

COM
.Visual Basic

" "s CPerson
.CPersons
CPersons CPerons
:Collections
CPersons
Private m_Col As New Collection
_ Public Sub Add(objNewItem As CPerson, Optional vKey As Variant,
)Optional vBefore As Variant, Optional vAfter As Variant
m_Col.Add objNewItem, vKey
End Sub
)Public Sub Remove(vIndexKey As Variant
m_Col.Remove vIndexKey
End Sub
Public Property Get Count() As Long
Count = m_Col.Count
End Property
Public Property Get Item(vIndexKey As Variant) As CPerson
)Set Item = m_Col(vIndexKey

195
End Property

Add-Ins Class Builder Utility



.

CCar objDrivers Collection


:CPersons
Public objDrivers As New CPersons

CCar CPerson
:
Dim BMW As New CCar
Dim Driver1 As New CPerson
Dim Driver2 As New CPerson

= Driver1.sName
= Driver2.sName

BMW.objDrivers.Add Driver1
BMW.objDrivers.Add Driver2

:


Item
CPersons Default Property
CPersons :

196
Print BMW.objDrivers.Item(1).sName
Print BMW.objDrivers(2).sName

Procedure Attributes
" ."OOP
For Each
CPersons :
Dim objDriver As CPerson
For Each objDriver In BMW.objDrivers
Print objDriver.sName
Next

Visual Basic For Each


CPersons
:CPersons
Public Property Get NewEnum() As IUnknown
]Set NewEnum = m_Col.[_NewEnum
End Property

-4 Procedure ID NewEnum
Procedure Attributes Hide this member 2-6
For Each .CPersons

197

:2-6 .NewEnum
:


COM OLE Automation
IUnknown
.IEnumVariant
:
Advanced Visual Basic 6
Power Techniques for Everyday Program
By: Matthew Curland
ISBN: 0-201-70712-8

CPersons CPerson CCar


3-6
.

198

:3-6 .CPersons

Visual Basic
Visual Basic
.Visual Basic
""

.

You might also like