You are on page 1of 408

Visual Basic 5.

~ 1998


. 21
- 189 03
. : (01) 46.63.419, 094-410.042
Fa : (01) 46.65.356
E-mail: poseidon@compulink.gr
Web: http://www.poseidon.gr/press


Q-ARTS . & . .
:
8 & 26
. : 92.41.571 -2
Fa: 92.31 .293

ISBN: 960-861-230-6
, ,
, , ; .
~o , - t
1.

,
.
,
.
,
. , -

. ,
.


Eo,ywrn -.uu

K~Wo 1
n n _
_
Textbox control _
Command button control _
_
_
_
(templaIes) _
- _
calculator _
_
_

K~o 2
( Project5 _
_
, project _
, _
Custom Controls _
project _
compilation _
_
_

_
_
_
_
(camparisan)

--

_

- - - - - - - - - - -- - -

--J
_
_
(Structures) ..,- _
Enums _
_
- (Object Variables) _
_
_
_
"" _
_
main _
U Visual Basic _
_
_
_
_
DoEvents _
_
11... Then _
Select Case _

_
(Melhods) _
_
(Debugging) _

Asserts _
_
_
_

Meru _
Menu Editor ~--:---,--- ------------------
Menu Conlrol _
Submenus _
,---- _
_
- menus _
_
_

--

K~o5

Mu/tLp/e - DocumeJ1t lJ1tert'r.ce () _


_
_
_
_

~o6
[a _
_
_
Pset _
line _
_
C rcle --.;

a i nt ctu re -
lilll
l -
DrawWidth ---iMill

DrawStyle ---1l1iii
FillColor FiIIStyle -------------------lIiiii
DrawMode ---iMilliil

-------------llil
---iiw

-----------------------li
oo

il
...........

a 110 ~
(mouse events) ~
8tt R'I
Shift ~
Drag and Drop
D
Drag and Drop
~
nT'I
n.

--
ll
K~o 8

) nJvv -1IiI
-IIIili
-----'...."""

l1 coTItroI5 ...
cantrals
Frame
Labe . '-.
nbutton ~
Chec kBox R
List ~
Com bo ~
Scro11 Bars n
Rle - System Controls
ore List
Directory List ;
""
~
"'
Fle ist ~
Time '
Imag e IIJ'
PictureBox ~
Shape rr.n
Line
Data - L
Custam cantrals rr.n
"'
~

custam contrals Visual Basic m


Com monDialog ~
MSC ha r rm
MSComm :w
SSTa b n
Microsoll Mail n
Statu sBar '!''
ProgressBar m
Slide r m
Imag eList m
...,,;
ListView
RichTextBox . .
Toolbar ..
TreeView m't
TabS

--
lll - -- - - - - - - - - -
I'r.'!"t
-
Animation ~

Multimedia _ ,----- -J ...


Microsoft FiexGrid ---------------------,
-

1IIi
.L2.

K&tPlvo 10

-------------1111ii1
clipboard -I
DDE _
D --------------------------IilliI
_
_

K~o l1

Datl C;oTItro l _
_
Data Contral -Iilill

data control _
RecordSource _
Recordset --I
data control, _
data control --Ii

Transactions - - -- - - - - - - - - - - - - - - - - - - --1
Bound controls _
Data Bound Grid control
Eo
1
---Ii

L:

O ~iIIiII
-----,----------------Iiil..
_
-,-------,------------------IiIiiiI
(Indexes) ---ii
DD - - -- - - - - - - - - - - - -- -- -- 11
Visual Basic 5.0 ------------Iii
D ---------------Ii
-iilii

--
index '

- -- - - - - - - - - - - -
(relations) (Referential lntegrity) _
--------------
D D _
SQL _
l (Aggregate Functions) - -- - - - - - - -- w
_
D _
DEETE -ii ...
_
- - - - - - - -- - - - W
- _
_

K~o 13
K_-,---- -iilil
l (objecl) _
l _
_
l _
--------------------IWI
_
OI Kl -liII~

l ll (objecl hierarchy) --- ----- --


-sli

----------------------lilil~
Automalion Servers -------- ------- ------ililil
w rd -5Ii

. -------------------lilliI
Eol -liiI1IiI

---"''-&8'''0

Ac;ttveX coJjtrol5 _
AcliveX controI -------------------liiI...
ActiveX Interface controI Ward -;i

l (Objecl Properties) -----------------lliiil


Enum ----------------J1iI
Extender --------- ------ ----- -Ilii8
Ambienl ----------------------iliil
oo ~

l Internet

--
controls


..o...,.,,..
OCX control, _
AcliveX control ' ----------;,;;
" " AcliveX control, -liI

, .CAB .INF -------------------Ii~


Internet, fIilil

ActiveX Oocuments ---- -----------------Si~


-II:.I~

K~o 15
nwj l t er et --
TCP/IP -IOIIIiJ

--------- ------ ----l iii..


(PortS) -------------------lil0IiI
Sockets ---li
Microsoft Winsock Conlrol ------------------liIiW
Winsock, lnlernel transfer controls TCP/IP -------------Cii
Clienl, -liI

Server --------------------Cii
Server -I1IOIi
UDP --------------------IlIOIill
Microsofl lnternet Transfer Control --------------~~1I
--------------- ------11i1..
SECURE ---- ----------- -fIill
FTP - - - - -- - - - - - - -- - - - - --c
, --'=:.

K~o 16

J)oj Help ------------IiI


HeIp project _
K, --1i11,;,

Help -----------------Ii
_
help ------------------
help Visual Basic _
K, --'=c.

Crystul Reports _
formula fields _

--
Crystal Reports Visual Basic ELL::

- -- - - - - - ------

~ _ _. _
__
IJII
--------------Im

Kefo 1.8

I/5: :5C; ------ -


Windows _
(Window Class) --lilill
O -iilil

AddressO! -------------- -------ililiill


..
U
.......

--
X ll
A ctVe){ DocurneJIts
Visual Basic 5.0
L. AcliveX
Document. UserDocumenl,
, , , '
OCX conlrol, AcliveX

Object Browser
Objecl Browser. TOl1lbar,
Code Window ,
. Object Browser
Visual Basic, ' ,
,

coJItrols
controls 5.0 , MSChart, MSFlexGrid, UpDown, Winsock
Internet Transler control.


.
:

l Typed Oplional
C+ + Visual Basic.
:

Public Sub SetTime (Optiona l lTime As Long = 10)

Asserts
Debug
(executable) .
.

Enums
AcliveX controls, ' .

Property OplionaI
, Properly Lel Property 6el,
(Optional argumenls).


, ActlveX conlrol,
Evenl, , RaiseEvent.

--

AddressOI
, (pointer)
" " . u Addre ssOf,

Professional
Visual Basic. ,
, , Hints &
, . ,
, - , .
,
Vi sual Basic 5.0. e-mail
.

r
E-mail: vbtrain@poseidon.gr
http://www.poseidon.gr/vbonline
1997

- - - -- - - - - - - -- --
--


Visual Basic 5.0, m project controls,
text boxcontrol commandbutton control.
, controls, .
, , ' button textbox,
Windows m ,
.

M ax im jZ ~B o x

SyntmMen.Bcx C apt.ion
( Clo~
Mi:i miz eBox
MeDJB",.

~~!IIIIIII""
EIle fd ~ ~e arch t!elp
_ _~
V etic ~ Scfol1 Bar

~ ClientAfe~

. 1 .1 . Wndows 95.

Visual BasIc, ' . 1.1 .,


, .

Windaws, , . ,
Visual Basic, Form ( ), l
,
( , System Minimize Maximize . .)
,
, controls,
. controls textboxes, buttons

--
, . OCX, Visual Basic, -

1
controls. , control ,
, (fonts) .. , .
control button. ,
, "" , ,
, . button, ,
xr 1.2.

: Fo rm1 I!lIiJD
Object: j Coua<nd1
~1~ e Sub Command l C!1ck( )
-
End Sub

. 1.2. yYOOD Click.

. control
, (events).
. , Visual BasIc,
( , controls . .) ; .
Windows events ( ) ,
.
. () , () .
, (project) ( .frm)
controls , , .bas (modules),
. frm
controls . , ,
, , .cls,
. ,
. ,

, :
.
controls (buttons, text boxes ..) .
@) events controls .

Kfo . Visual Basic 5.0,


; 1.3.
, Microsoft .
, Toolbox - controls
Visual Basic - Project Explorer,
project projects (groupprojects) .

--
Toolbars .

2
t) ,,"~'tI-~.V-~ .o<> l_~,",, ~ _toiI> .&Wl!J
.; - ~ . " ~g P<tI .., r . ':!.~_~:'5~
, ~ . ~ /;i. (j . ;j. $ 8

.1

. '

-
.:J

. 1.3. i su al Basic5.0 .

, . ,
. ' cl . '
, ' cap~on (back-
ground). " Propertes Windows" Toolbar Visual Basic, "F4",

1#1.:.11

!Form l Form -.
:] '

-- ,." ""
,. .,
...........
Nme ) F om l

,

~i!.Z
~
. Siz
F_ I
,~
...
,~

I3CoyPtro

,
"""

...........
,~

'n.e.... ""
- ..-.sprett

" onoor....,
"'
. &--t(OIOO ~

X:bon
Rensjsets thetM: dspI.ayed rI n clectS.ttIe b.:

. 1.4. .

, '
' . 1.4.,
.
(design ~me),
(run ~me) .

-- 3
,
:

Appearanc. , Button Face Control Panel.


AutoRedraw , ,
. . , , , -
, m
Pain! . , m .

BackColor . , -
.

Bord. rStyl. ' .


:
- None: Ii .
1 Fix.d Singl.: .
2 - Sizable: '
3 - Fixed Double: .
4 - Fixed ToolWindow: . -
Windows95task bar Maximize Minimize buttons.
5 - SizabI. ToolWind ow: ' . -
Windows95 task bar M aimize Minimize buttons.

ClipControIs True, /
.

ControlBox . - fais. Control ( Syst. m M.nu ) .


Control , Bord.rStyl.
1 (FI.d Singl.), 2 (Sizable), 3 ( F.d DiaJog).
Icon , minimized .

KeyPreview (d.faull) faIs., . ,


control .

MaxButton True - False Maximize .


MinButlon True - False Minimize .
Name / . , control,
. , u
/ .

S!artUpPos"ion
.

Tag .

Visible ru. - fais.

WindowStat. . - Nonol , 1 - Minimized, 2 -


Maximized.

Left , Height Width


. ,
. controls.
controls , .
Toolbox ! 1.5.

--
control , , -

.
, (dragging) .
, , ,
.

~ ~A

I'b "~J
r. " !J
lm :!!! .~
ll 'O
~i--"
1OiJ ~ 'i!

. 1.5. oolbox, controls .

Textbox coJjtrof

~ text box control,


. 1.6., control
( F4) .

. . ". "." .. .
.. :I;~' .

. 1.6. text box control .

1.6., control , 8
, ' , , '
.

--
text box control,

5
. .
:

Locked textbox.
MaxLength control .
MultiLine True - False control .

PasswordChar ~
. , .

ScrollBars m , -
ovo , - , 1 - H oZontal , 2 - Ve~ical , 3 - Both, -
, , , , .

SelLength .

SefT eX .

TeX tet box control.


control.
, controls. :

Appearance controts. control.


BackColor contol.

Draglcon / OVKO "drag -


and - drop". / / , control
control. / .

Container control / control.


DragMode dragging "drag and - drop".
DLEDragMode OLEDropMode, " .
Enabled control. control
.

Font (object), ooJ / -


. :
a. Name , .. Anal.
b. Size .
c. Bold, Ilalic, UnderIine, SlrikeThrou gh ovo x .
d. Weighl u " " .
u , 400 700.

ForeColor control.
Height Jo control. controI.
H e lpCo nle XI D , , u (Help) ,
F1 topic. u
.

hWnd (handle) TOU coOOol. u ouvopTir


.

Index m controls
, . contrOI
( control)
32767 .

-- 6

Le" control /
.

Linkltem, / a Windows ( Visual Basic),


LinkMode, , DDE.
Link Tlme out, .
LinkTopic
Name control controJ.
TabIndex cno cantrals "Tab" "Shift + Tab".
UKKpO control n - 1,
n controIs .

TabStop cn false, cn cna


control "Tab- "Shift + Tab-, U True.
control
.

I,;sible True - FaJse control .

Width u control. controI.

CJJl(jd but t oJ) c ot ro l

~ cantrol Command Button npo ,


(event),
nK p, controI,
. [.

1!t#ftI'' @ffl! iiihffl l : M C.O ' MII M !

IConw>d ~ ::=::J

"......" ",,
~ ICateQOflled

t~=~=::~~~ ,.",
""""""'.
,
,""""""
Hffl
->
->
- >
......
,
~~-'~,'"
~

~
MS Sns Setl

--
. 1.7. command bunon control .

7
,

C.ncel , control u " ",

C.ption u nou controI. u u u


access key, TOU u "&", u
, control uu
" A/t" + ,, .
Def.ult True, control u "Enter" .

, (events)
cantrals ( , ) . ,
. cantrals, text
box cammand buttan cantrals. , : text box,
caption command button
, b tton caption .
controls
. 1.8. .

_ lal,

~ : ' : ::.

"""""'" :::: ..

. 1.8. controls .

, textboxcontrol.
( control), editor,
'
CodeWindow. 1.9., editor .
(Object) controI ( Name), (Proc)
o ~ control, .

1~1
Pr l v a l;e 3
J
T"xl;l_ Ch.. n",,, O
1-- .
J

~
3

~
-

,.~
~
..- '.
;&

--
. 1.9. Code Window text box control events.

8
, editor (
' ) , :

Private Sub Contro lName-EventName ()


End Sub

ControlName Name control, EventName


. control controls
ControlName. :

Pr ivat e Sub C o ntrolName-Ee nt N ame (I ndex As Intege r )


End Sub

, Index Index
control. ' controls event.
Object, control '
' events ( 1.10).

. 'rfffi'0ftj'$ _tol )(1


I ed1 !Cho
=.
........,
~

.m

,
-: !
~~ ~I
. 1.10. conlrols, .

events textbox control. control


(Name) Text1 controls. eventChange,
text box. :
Private Sub TextL-Change ()
End Sub

events controls. ,
. Clck DblClick
control, . event GotFocus control
( ) , , , LostFocus
( ' ) . events
Change.
controls , .
Form Object, Proc even-
ts ( ) . . event
Laad , . :
Pri v ate Sub F o r...Lo ad ()
End Su b

-
~ - - - - -- - - -- - - - -
Unload . ' :

Pr ivat e Sub Form-Unl oad (Canc e l As Int ege r )


End Sub

Cancel , ,
Windows event QueryUnIoad.
.

Click / .

DblClick .

MouseDown, . .
MouseMove,
MouseUp
KeyDown, . .
KeyPress,
KeyUp
Resize .

Paint .

, Change lext
button conlrol :
Privat e Sub Text L-Change ()
commandl .Caption = t ext l . Text
End Sub

controIs
, .
(read only),
(read - write) . Caplion command button Tex1 text box
control ' . , ,
:

FormName!ControlName.P r o pe rty

events , FonnName,
:

Cont ro l Name . Pr op e r t y = NewVa lue

conlrol, :

OldValue = Cont ro l Name. Pr operty

. ,
, , caption button
lext box contraI.
,
, Click button Command2:

--
10
Pr iva t e Sub Command2_C l i c k ()
command l .Caption = command2 .Capt ion
End Sub
Caption button command1 button
command2, " " .
" " , "F5"
Start Run Visual Basic. ,
, 1.1 1.

Fo rml I!!I~EJ

. 1.11. , .

,
, " " Visual Basic.

designtime
, 1.1 2 . View Code
codeeditor controls ,
Editor ,
.
i; F onl1 I!!I~EI

: . -

. 1.12. .

Lock Controls " " controls ,

--
. Paste

11
clipboard, , , Properties .

" " Visual Basic,


() ,
Visual Basic. . Save Project
As... File, ( 1.13.),
( project1.vbp), vbp. , ,
Save Fle As... .Irm

)>> !f4#, ?~1

. 1.13. .

, , Open Prajecl...
File vbp. , New Project
project . , mod-
u1es ( )
' Project Explorer ( 1.14.).
View Form , View Code
,
events controls .
, ( module ) ,
( Name). ,
, , modules .

!
Ei ! fl -
8 ~ Ssmd (5smd3Z.b)
, ""'"
&<S
'- ~ AIcwOtjrs(AIoYoot:.fr)
;- ~ 8cm=orm (lrsr.-.,. Frm)
j- -t1 CoIor1'm (CoIofs.FRM)
,, ;- t1 find:>lo (~. frm)
- ~ IM.F. " ;j
tl ShowOtQns ($howOpt,frm)
f __t'1""\ :: etdform (VTIChiId.frm)

""""'"
"--.::.ssr-cH(S5HJl.6A5)

--
. 1.14. ProjecI Explorer .

12
frm vbp,
. File Make ...
1.15. .

..- ?

S_tr I~ E uIe J m1 ~I~

FIe Qme:
1-
Ir ~
-..-
~

. 1.15. .

, (Application Ti~e)
(Icon) , , ,
Intel p-code.
OptIons... . ( 1.16)
Make Compile. p-code
(Compile to P-Code) Intel (Compile Native Code) .
(optimizations) in .

--
utMMi!t@' ;M'.!

~I~ I
Yer sionlnber

~IO<'


.
., ., ,"";11,
- ItIe': 1,I,0000
.. -
IF;nI
/>4OInernen:
k
D.
Yt<SIOfI l'it:rl'MtiOtl
?', :!:......:

It,;.;,_..... )J :J
.:J
~I$IeArneds'
ConJIj:/I~~,1
--
c::::::J'~ ~

. 1.16. .

Visual Basic
Intel (native) p-code.
. .

--
native .

13
5.0. d,
Visual Basic .
' : run time Msvbvm50.dll,
( ) .
native ; (optimizations)
. VC++.

Pentium Pro .
(debug symbols) .
LL debugger, Developer Studio
VC ++. (multithreaded)
( 5.0),
threads Visual Basic.
( ) , Msvbvm50.dll,
, , custom controls
OCX, , ,
System Windows, reg-
Istration, . , Setup Wizard,
DLLs OCXS.

'

Add Form Project


.
, , ,
, (templates),
.

'-'4 ;
NZ=:I ~I

- . ::: #.
.;;:.
\lBDat ~F<r",
Wizard
.
.oJ>out Oi<>Iov
::: :::
L09 In ~ Oti<n. DiaIog
"'
? !

:::
s,s! So:r~

... ~
:::
" n.

'"'-
:::
".'"
:::
ODBCLo ln
.-
:::

..::

Di:J
""'"
[~
I r:oon~ mowt~ <lo ir he ly1ure

.1.17 . .

AboutDialog, The Day . .

-
.-
1-4 - -- - - - - - - - - - - - -
-

calcuJatol
boxes controls command button.
commandbutton, 30 box control boxes controls.
Visual Basic , boxes controls
commandbutton control. control Text3, Locked nu ,
. .
CodeEditor Load , :

Private Sub Form-Load()


Caption = "Simple Ca lcula t o r "
End Sub

Load . , ,
(caption) . ,
command button control, :
Private Sub Commandl-C lick()
, tXEl n

If Textl.Text = "" Or Text2 .Text = Th e n


MsgBox " i" , vblnformation,
" "

Exit Sub
End I f
\ Q

Text3. Text = Va l ( Text l .Text ) + Va l( Text2 . Text)


End Sub

,
. Val,
. ,
. 1I - End 11
, . ,
. F5, 1.17.

1=

""

. 1.18. .

--
15
,
File Save Project As... ,
, , exam1.Vbp.

1.
Visua/ Basic; m.
Basic DOS -

2. project r Visua/Basic;

3. ;

4. ro Too/box, ro ro code window;


5. rT ;

6. ; r.

7. n ro cantro/; contro/s r rT ro.

8. r rra tndex control.

9. (events); r , ra
text box controt command button control.

10. OCXcontro/s;

11. r p-code native


code;

1. tet boxes
controls command button control. . focus tet boxes
controls, . , command
button, ' caption tet box control.

2. command button control. OviK


, control . ,
.

--
16 - - - - - - - - - - - -- - -

Projects
project.

[
,
projects.
:
(.FRM).
, controls (properties)
(binary) , (.FRX).
(.CLS).
module (.BAS).
custom controls (.OCX) .
resource (.RES).
project (.VBP) .
project ,
,
. , Project Explorer
project, custom controls.
project,
in-process DLLs ActiveX controls.
, Project Explorer projects '
Project Group, .vBG.


Visual Basic:

form Modu/e5
.FRM , ASCII, ( )
controls , (form-Ievel)
, , , (events)

--
.

17
crfA~~ IJ o d u I e~
class madules, ,CLS, madules ,
(user-Inter1ace).
, ( Visual Basic).

StfAdfArd Iodule~
standard madules, .BAS, (public) (fa m - level)
,
.

Re~ource~
Resources, .RES, ASCII
, bitmaps, . . , ,
, resource
, .
resource, , , , resource
ed~ar campiler, AppStudio m Microsoft Visual C+ + .

Cu~t orn COJltr ol~ I JI ~ ert fl b' e O b) e ct~ ( )


ActiveX L Custom Conlrols .OCX I nselabl e Objects
,
. Visual Basic, ActIveX custam
controls \WINOOWS\SYSTEM.
I nselable Objecls , Microsoft
Excel Netscape.
ActiveX Microsoft
1996 L contrals Internet.
" " controls Web
. , AcbveXcontrals, " "
,
, . ,
"" L controls,
ActiveX.

StflJldflrd COJltroI ~
Standard Cantrals Visual Basic
Toolbox, L ActIveX custom controls, Inselable Objects,
Taalbax, . Standard Controls
textbox c m man d button cantrols . .

, n ~ project
File, ,
project Projecl Group.
praject, New Praject. praject,

--
-

18
2.1., project . default
Standard .

~
@@,
908
ActiYeX EXf
17
A;tieX/

-
17
C""'.
'"
1"~ck' l
"..


:~"
"',,'"
~
Ac.tiveX
~
s Ak4ton Enterprse

"'"""
cor trols
~
- ~
Act~

-""
'- ... -
. 2.1.
-
.

ActiveX , L
Automation Serer , . ActiveX DLL
in-process L Automation Serer , ActiveX control
ActiveX controls. Application Wizard wizard "
" , , ,
Web. ActiveX Document DLL ActiveX Document in-process ActiveX L
Automation Sere rs " " Intemet Expiorer, Addin
template add-in Visual Basic. ,
Enterprise Edition Controls EnterprIse Q controls
. project, project,
, Open Project project,

project. Project Explorer , modules
project, Toolbox custom controls.

Add Project project.
in-process DLLs ActiveX controls.
project group, projects.
project, Save Project Save Project As
project form, standard class modules

project. projects, Save
Project Group Save Project Group As, projects
project group.

roo~Jj , n~JjJ)

Proje ct,
, Form, module, class module, User control . . ,

--
, ' '

19
. , Remove ... ,
Save ... Save ... As File.
projects project
(references) . .
drag-and-drop
Explorer Windows, File Manager Netword Neighborhood Project Explorer
. .OCX, " " Toolbox.

I1poo~j a{po c.ustOJJ C.oJjtrols j

custom controls, toolbox.


Project Components (Ctrl + ) .
2.2., L ActIveX
custom controls, insertable objects. ' Toolbox,
check box control'
, controls Toolbox.

ComponenIs

c,,",," 1- , ....... ~'"


[] fkrosoft AutoFl Control
Mosoft Candar Control8.0
l'Iosof CNrt (
:J Hosott Com Control5.0 (SP2)
~, 0

D MosoftComecn~ S. O (SPZ)
OMicrosoft ~ Bod Gd Control
O Mi:rosoft Dt" BOt.Ind List ConI:rols 5.0 (SP2) ! j
D Microsoft FeGd Cootrol5.0 (SP2)
D Miosoft Forms2.0 Object bI'fY
MiosoI' GrldControl

.
[] l'Icrost Intemet:COftrols
O lo'crosoft Intemet Transfer CortroI 5.0 (51)2)
~
.:.:J
..
Mosdt Cnor DaIoJ (000015.0 (SP2)~~",,"~~~~~'i1
~0Y>'Se .

I.obon: C:\WII'OOWS'\SYSTEM\CCMX.G32.00:

. 2.2. nAoimo custom controls.

, ,
check box Toolbox. control
,

l1n pro)ect
Project, Project Properties,

--
project project, ' project .

20

ProJ<<;t !i=:
IProe<t!
!j$fl>""""


" o ;.: DesVO" "

. 2.3. project.

General ,
.

ProjecI ' u project Standard , ActiveX , AcnveX L L ActiveX control.


Startup Form , "" project ( time), -
Main . standard module.

ProjectName project .
(.) .
Help File Help project.
HelpContextlO context 10 topic Help, -
F1 , (object library) project
Object Browser.
Project Description project, Object Browser.

project Make,
Compile p-code native code. ,
Component standalone
ActiveX S ere r (ActiveX Component).

'{ (1} comptlfttOJJ

Visual Basic 5.0, ,


compilation, . compilation
# 11...Then # End 11,
(True) (False) . :
~If Pers ona l Then

#Else

--
#EndIf

21
, compilation Personal True,
, .
compilation.
Make Project Propert es , Conditional
CompiIatIon Arguments Personal = 1, .
, :

Personal=-l : English=l: conANS I =O

command iine, /d,


:

Vb5 / make Gaia.vbp / d Greek=-l:Persona!=O

, compilation declaration
module,
'Const Greek = True

Project Properties

declaration
module. , ,
' modules , ,
module.

1.
;
projec/ S/andard.

2. projec/ .
. projec/s ;

3. modu/e. ;

4. cus/om con/ro/ .
.

projects,
module.

--
22

OuickBasic OOS,
Basic. -
, , OOS.


V sua l Basic (procedures) (functions),
OuickBasic.
(Oecision Stn ctres) ,
, modules
. .

.
, ReOim Preser e,
. .

- .~p

.
. ,
:

"" +

, .
,
. ,
,
. :
(string). , .

. , :

--
23
- 20

2 bytes . ,
, -32,768 32,767, 2 bytes.
-2,147,483,648 2,147,483,647,
4 bytes. ,
,
.
$, , .
:

$ = "Visual Basic"


,

( . . , , Tabl .. )
() . [ [:
.
@ ( . . + + ) ,
- +
, ..:

* ( - ) 1 1 * -

@) ,
. , ;
: ( + 1) * (C-6) : ( + 1) (C -6)
:

+ * / C - 55
10 * + Si n ( X) + 3 . 4 * Co s ( 3 . 14 * )

D~J)v Dwv
:

Mod

MyNumber = 2 + 2 4.

--
24
MyNumber = 4 257.04 + 98112 E ~ ~ 102369. 04 .
MyVa lue 2 2 .. 4.
MyVa l ue = 3 3 3 ~ 19 683 .
My Va l ue = ( - 5) 3 ~ 125.

My Re s u l t 10 Mod 5 . .

MyRes u lt 1 0 Mod 3 1.
MyResult 12 Mo d 4. 3 . .

MyNumber 'j. i Rem


(') .
,
:
.
f9 ,
:

1
.

2 / , .

3 +- .

4 +- , .

~ onoia i
. , , = +*C/+-F 2
i :
1. = FA 2
2. = B*C
3. = /
4. = +
5. = +
6. = -
, , , . .

--
. 3.1. Cray-1 100 .

25
Visual Basic D READ Basic.



(concatenaUan). u ; & +. , , :

$ = "Vis ua l"
$ = "Ba s i c "
C$ - $ . & $

C$ Visual Basic.
+ ,
.
, .:

Varl = "34": var2 = 6


MyNurnber = Varl + Var2 \ E ~ ~ 40.

Varl = "3 4" : var2 = 6


MyNumber = Va r l & Va r 2 101 "34 6" .

(:) .

(crnur)
C , .
;
' C :

- ...

<> ...

< ...

> ...

<= ...
> ~ ...

;
, : (True)
(False), -1 . ,
, = 1 = 4, :

= False <> ru e

> False + 4< *2 True


< Tm, < = Tru e
,

--
. Visual Basic Basic

26 - -- - - -- - - - - - - -
ASCII.
(
32) .
, ,
, , .. "ABCZ" " ABXl"
.
, , .. ,

"ABC ">HABC"

True, .
, MySesult
:

MyRes ult ( 4 5 < 3 5) E ~ o ~ Fal se.


MyResult ( 45 = 45) E~ ~ Tr ue.
MyResu lt ( 4 <> 3) 1 0 1 True.
MyRe su l t ( "5 " > "4" ) : . : Tr ue .

Va r l = "5 ": Va r2 = 4
MyResu l t = (Var l > Va r 2 ) \ n l. l. Tru e .

, ,
(LogicaI) ,
, And, Or Nor. .
And :

res ul t = expre s sionl And expre ssion 2

True, True.
False, False.
:

~ 1 0: ~ : C - 6
My Che ck A >BAndB > C True .
MyChe c k B > A And B > C . Fa lse.
MyCheck nd : ]. 8 (b i twi s e : ) .

Or :

result = expre s s i on l expr e s sion2

True, True.
:

-
MyChe ck
10: =

:

>
C
Or
-
6
> C : : Tr ue.
MyCheck > Or > C l. : Tru e.
MyCheck Or 1 0 : 1 0 (b i t wi s e .}.

, :

resu lt = Not e xpress ion

--
27
, True, False .
:

~ 10 : ~ 8: C = 6
MyChec k No t (A > ) E ~ 1 False.
MyCheck Not(B > ) 10 True.
MyCheck Not 0 - 1 1 (b i t wi s e 0).

bitwise bits .
' 1 (bit).

v aJjv
.
:

Integer % 2 bytes -32,768 32,767


Long(long in!eger) & 4 bytes -2,147,483,648 2,147,483,647
Single ! 4 bytes - 3 .4 0 2 8 2 3 3 8 -1.401298 -45
1.401298 -45 3.40282338
.

DoubIe # 8 bytes - 1 .797693 13486232308 -


4 .9406564584124 7-324
4 .94065 645 841 247-3 2 4
1.7 976931348 62 32 308 .

Cunency @ 8 bytes -922,337,203,685,477.5808


922,337,203,685,477.5807
String $ 1 byte 2 32 .

Byte 1 byte 255.


Boolean 2 bytes True FaJse
Da!e 8 bytes January 1,1 00 December 31,9999.
Gbjec! 4 bytes .

Va r ant 16 bytes + 1 byte Null, Erro .


Variant, default
Visual Basic. (Integer, Long, Single . .)
, (date,ltime) .
Variant ,
. , Deftype ( De!lnt
-) , Variant, Dim
, 1.0 Visual Basic default
Single. :

o im var iablename [As type]

Variant ,

--
VarType, :

28

vbEmpty Empty
vbNull 1 l l

vblnteger 2 Integer
vbLong 3 Longinteger
vbSingle 4 Single
vbOouble S Oouble
vbCurrency 6 Currency
vbO,te 7 O,te
vbString 8 StrIng
vbObject 9 L Autom,tionobject

vbErro 10

vbBoolean 11 Boolean
vbVariant 12 Variant ( u Variants)
vbO,t,Object 13 Non-OLEAutomation object
vbByte 17 Byte
vbArray 8192 Arr,y

, Visual Basic 5.0 '


. ,
' vco xo . Empty
, l l
, i i.
. Command1_Click "" button.
Visual Basic l i text box
Varianl ( l$ cp
). IsNumeric i
. i , IsReal ( i
) i ,
Num Variant Single Double . ,
Visual Basic MsgBox i i .
Private Sub Commandl-Click ()
Dim Num As Variant

Num = nut(~ .")

If I sN ume r i c (Num) Then


Num = CDbl(Num)
Else
MsgBox " ."

Ex i t Sub

End If
rf IsReal(Num) Then
MsgBox " (real nurnber). " Else
Ms g Bo x " 6

--
29

- - -- - - --
( real number) ."

- - -- ---
End If
End Sub

Functio n IsReal(VarArg As Va r i a nt ) As Int e g e r


I f VarType (Va rArg ) = vbDoubl e Or Va rType (Va rArg ) = v b Single The n
I s Re a l Tr ue \ Ol Single Do uble.
El s e
IsReal Fa l s e \ ,

End If
End Func t i o n

11 End 11, . .

Visual 8asic IsNumeric Variant.


IsDate, (dateltime) . IsArray
, IsObject L Automation, IsEmpty
Variant . . IsNull,
.
,
(#). Variant SomeDate
. :

If SomeDa te > 118 /5 /631 then

, :

Dim S As String

(variable-Iength string)
(f ie d -Ie ngth string):
Dim S As String * S i z e

size ; ( ) . strIng
, string , :

Dim i ntX As I nteg e r


Dim strY As String

st rY ''10 2 . 4 4 ''
intX = strY

.
. Basic (
, C Pascal), default .
deciaratian ( . 2.3.) module :
Opt ion Ex p l i c i t

module Dim.
:

Deflnt -

-- 30
declaration, Integer .
8asic,
; .

. ' !,.,. _! l
I j General)
J ! (DeClar8t iOl1S)
J
Optio lJ Expl i c i t

Pr i v a t e 3 ub Fo r m_ Load ()
..
End 5 Ub


-;
3 I ..1..:J ~

. 3.2. Declaration .

Dim ( StatIc)
(Iocal) ' . ,
Dim Declaration
module, module.
(global) ,
. Declaration module (
) , Public Global, .
Declaration lorm module,
Public. , :

Public ID As I n t e g e r

Declaration Form1 ,
:

Form l. ID

Private Dim,
Module .
class modules Public
.
3.3,
module CITelnet.Frm, module.
, 3.4. Public
modules . , module Modem. 8as
Const. '
.
& , WM_USER .
.
Dim StatIc
, .
, Static
, :

Stati c Func t i o n FunctionName (args )

--
31
' .1, ,,:., _ l '
11~ I) J Ine-,,-I J
l1 c

::J
,.
~
-.: a e 1D01:I,s.xlte !.3 Cb ) ee >:. ."", P['QCo"",,Co nB :o l
( :

.:ae 8Ob,laulat.or !.3 Cb, ec>:. ''''',


. "..
C l> <,l

P-':lvat.e .," _ u St.-':l no;1 ~" ",.""

P-':l v a t.e _Bollt..usd.r l!"" St.-':lno;1 . ".. ~O", dc1-.:I!:"


P<'lva>:.1I! _Slt-':V1CI!
v a e _~O oll
"
U
U
S>:.-.: lno;1
S -': l nQ1
'~ I! -': "' lCe 51! a rl! c n ~ t. l: ;

rvae MCnneced U Boolean 'A re ~ cc' l,nect ...d'


rvae ob Eeho Boo lea n '-':! ...<"OO 1ng1
riae ..iSendCo lor "
U Ir,t eQer
~

riva.e ",iReceiveColor U n eQ er

rae ",IC "ar ne; er


Pr l v a t e "'i rr rC. "" nte; er
i~r l Vat e rbGoJ.hl!ad
": ~ " Boole an ". ", :ren d Z',l. ll rA IS?
.,fj

. 3.3. module CITelnel.Frm.

M ibffi , 4 ' I ' j : M ! $ ' _ ! '

J
P ub l tc ( = lPP NAm .. "G a 1 . D e 1 u e"
P ubl1 c (= lI'R_Us ER - ' 11'100
Putll l C ( Il5 TJU.NS_CNC L
Putll l C ( 5 TJUNS _R ENJ.llE
Putll1c ( = TRllIS OVlRVR I Tt
: Co = t 111<1<1e; Con fe re nce . ...... !a _",,,age,,, "
Putl l I C Co=t Gal a !Iir:er "'io n '" ~Gala i1J!!:-Ver 5 1 0 n : 1 .0"
: Co = 1;., COnt en>:._Type " c on>:. e n >:. - Tvpe :"
P ubl lC Co ns1;., C OD t.eDt_Sl~ e "Cn>:.en -S 1::e: "
PI.IbH c Co nst 1'1...",,,, I d - " fIe ",,,,a oe - ID : "
-
Pub lIC EIb I! 5 Lono Enable_Co nf... ...nc... 5 Inte oe r
,. :~7 '~. ~ r-~.? ~n_e :;.~I:'~A:""-"~.~.,,,,~.,,n~ ~

. 3.4. GlobaI .

Visual Basic .
, Currency, CCur:
Pa y Pe r Wee k = Cc ur ( hou r s * h ourlyPay)

(con-
version function):

Cbool Boolean CLng Long


CByte Byte CSng Single
CCur Currency Cstr String
CDate Date CVar Variant
CDbl Double CVErr Error
Clnt InIeger

--
(array) . ;

32
Visual Basic Basic.
, Dim Redim.
, .
. :

Dim (4 0) , Con (lO ,15 )

41 . 11
16. :

() 256
(l) = 324
(2 ) = 100

(40) = 55

.
1 ( ), :

Dim Ar (l 40 ) As String, Con (l 15) As I nteger

, Declaration, :

Opt ion Bas e 1

, Dim,
Declaration module. ; , '
.
module Dim
, Declaration, :

Dim DynArray() As I nteger

, :

Redim Dy nArra y () As Integer

( ) ,
Redim Static Dim . , Public Global Dim
Declaration,
j modules , :

Publ i c MyArr ay(45) As Integer

, :

Public MyArray( ) As I nt e g e r

.
( )
.
,
. EuX , Viusal Basic Preserve,

--
Redim. ' ( ) , -

33 - - - - - - - - - -- - - - -
.
' ' .
,
, :

Redim Pres e rve MyAr ray( UBound(MyArray ) + 1 )

UBound , LBound
. , Erase (
) .
(Long Integer) , - 2 3 2 232 -1 .
Array,
. Variant
. :

Option Base 1

Dim My Week, MyDay


MyWeek = Ar r a y ("Mon " . "Tue" , "Wed" , "T hu" , "Fri" , "S at" , " Sun " )
MyOay MyWeek( 2 ) MyDa y 1 1 "Tue" .
MyDa y = MyWe ek ( 4) MyDay 1 "Thu ".

Array
Data Basic DOS.

j (Structures)
Visual Basic
,
( ) .
Type . Declaration
module. , Private. ,
.
, Declaration module:
Type Sy stemI nfo
CPU As Variant
Me mory As Long
Di skD r i v e s ( 3 0) As St ring
Cost As Cur rency
End Ty pe

Systemlnfo . :

Dirn My S y stern As S ysteml n fo , AllSys tem() As S ystemI n fo

Systemlnfo.
, , :

MySystem. CPU = "4 8 6DX"


My S yste~ Disk Dr i ves ( O ) = "1.44 "

--
34
AllSystem(2) .CPU - ' 3 8 6SX'
AllSy s tem(2) .OiskDr i ve s(1 0) " 1.44 MB If

AllSys tem(l) = MyS ys tem

.
( DiskDrives ) . . m
Declaration Standard modl e, ,
Private Public, modle
. ' Form Class modl e , .
, Systemlnfo ' Standard
module :

Public Type Systemlnfo

End Typ e

ET1um5
Visual Basic 5.0 enum,
' . :

Privat e Enum DaysO fT he We e k


Sunday = 1
Monday
Tuesday
Wednesday
Thurs day
Fr iday
Satu rday
End Enum

1 Sunday, 2 ( ) Monday . .
, :

Di m Week as DaysOfTheWeek
ArrivalDate = Mon day
! ArrivalDate < M on day Then

){nj nv
(collections) ,
,
. ,
ReDim.
, .
:
Pub lic co lURLHist ory As New Collection

Add ' :
co l URLHi s to r y . Add URLAddress

-- 35
oi] :

Dim URLAdd re s s As Variant


For Each URLAddre s s in co l URLH i story
Debug .P rint URLAdd r e ss
Ne x t URLAdd r e s s

13.

- (Object l'l r l'l b r e ~)


, cantrols,
oi] (
) . Visual Basic
.
Form1. :

Dim F As Fo rml F. Sho w

F
Form1 .
Form1, :

Dim F As Fo rml, As Forml

F.Caption = ~ New title W


. Show

,
, Form1 .
New Dim. , :

Dim F As New Forml , As New Forml

. Show
F.Show

(instances) Fomn1 ,
. , :

ReDim fArray (2 0 ) As New Fo rml

' control :
Dim a ny Co nt r o l As Cont r o l

control , ! bo:

Dim anyCo nt r ol As TextBo x


, , controls. .

--
. , Form1:

36
Ca l l Sh owForm (F orml)

Sub Sh o wFo rm (for.mx As Fo rm)


fo r.mx. Show
End Sub

text
box control. :

Sub fillTex t (Source As Cont ro l , va l ue $ )


If Ty peOf So u rce Source Is Text Box
Sou rce . Text = va lue$
End I f
End Sub

1I ... I EIse11 ... I


control.


Visual Baslc 5.0 (
) .
NoKeyPress.
Declaration NoKeys:
Pub l ic Ev e nt NOKeyPresses ( Key$ )

KeyPress :

Private Sub Form-eyP ress(KeyAscii As Integer )


RaiseEvent NoKeyPre sses (Chr (KeyAscii
End Sub

" , RaiseEvent .
NoKeys, Dim, , W1hEvents :
Pub l i c WithEv e nts Foo As NoKeys

Set Fo o : Ne w NoKe y s


Fo o .Show

, :

Priva t e Su b Foo-NoKeyPress e s ( Ke y$ )
MsgBo x ~ 1 \n & Ke y$
End Sub

>

Visual Basic Irm

--
m , modules ( bas), ( CLS ) , ,

37
OCX .
events controls .
(private) , module.
public, .
modules. ( )
(
public, default standard modules).
,
, ,
Sub, Function ( ) Properly.
.
Sub , , Property
(custom) .
Sub (procedure) .

[Pr i var e IPub l i c ] [Static ] Sub procedurenarne (arglist )

End Sub

Sub Pa r s e Pa t h (file $, d %)

End Sub

ate , , fomn
standard module , Public ,
. , Slatic
, .
(default) Private, ' standard
module Public. .
(arguments) ,
. .
:

(ByVal ] var i abl e n ame [( )] [As type]

" " by reference.



' , ' . ByVal,
,
. " " ,
, :

Ca l l Reve rse ({ V), 5)

Ca l l Parse Path ( ~Dernon , al u e %)

--
Pa rsePat h "Derno " , va l ue %

38 - - - - - - - - - - - - - - -
m SomeSub Public ' module
Form1, , :

Ca l l Fo rml. SomeSub(a r g uments)

lorm module, Fom1 .


, standard modules public. ,
' , ,
modules, module:
Modulel .CommonSub(argume nts)

, Exl' Sub End Sub.


Windows
(even's), ,
, .
, (resources)
. Visual 8asic
Windows.
( , )
:

Pr ivate Sub Form-ev entname (arg ume nnt)

End Sub

, Form
eventname , :

Private Sub FormLLoad ( )

Form1 .
.
, controls ,
' button text box con'rol. :
Private Sub Co ntrolname-eventname ( a rgurnents)

End Sub

Controln ame control , , (unique)


. Public Priva'e, default
, ,
' .


, . Visual
8asic Sqr, Chr . . ,

--
. :

39 - - - - - - - - - - - - - --
[ Pr i v ateI Public] [Static] Function f unctionnarne ( argli s t } [As t yp e ]

End Function

, Prvate , Public Static.


. ,
. ' ,
:

fucti o n arne = retvalue

Func tion Exist ( fi l e $ ) As Integer

Exist = re t %
End Funct i on

ex% = Exist (filename$ )

Function End Function.

:

(property procedures)
read-only ,
standard modules .
, module . Visual Basic
' , :

Property Let .

PropertyGet .

Property5e! ' .

,
Inverted . Public
module :

Publ i c Inve rt e d As Boolean

Forml.Inv erted = Tru e

V = Fo rml . Inverted

Private,
,
module. . Private
Islnverted re LeI :

--
Pr ivate IsInverted As Boolean

40
Property Let Inverted ( As Boolean )
IsInverted = !
IsInverted Then

El s e

End !
End Property

, j ' uj :

Forml. Inve rt ed = True

j .
Property Get.
Pr operty Get Inverted ( ) As Boolean
In verted = I sInverted
End Property

oj:

Property [Get ILetISet ] [Static ] propertynam e [ ( arqument s ) ] {AS type]

End Property

Xjo , Property Get


Property Sel Property Let. ,
Names:
Property Let Names ( As Integer, As Int e g e r, As Variant )

End Property

Property Get :

Property Get Names ( As Int eger, As Int e ge r) As Variant

End Property

Prope1y Le! [o bj ect] . p ro pe1yna me [(a rg u me nts)j = argument


Prop e1y Get vanable - [object]. prope 1ynam e[(argum ents)j
Prop e 1y 5et 5e! [objectj .prope1yn ame[(arg umen ts)j = vanable

Property Sel Property Lel,


. , Visual Basic
j Kj . , , a, b,
c d w, , :

Demo ( a, b, c ) = d

--
"1
Property Le t Demo (w, , , )

End Property

, praject PROP_IND.VBP.
Property Let Property Get,
. , text box
j , , command b tton, label control
lndex . Label controI .
. lndex textbox
command button, label .
Declare ,
, intlndex, .

Private vntDemo() As Va r iant


Private intlndex As I nt e g er

Load , ,
.

Private Sub Forffi-Load()


ReDim v ntDe mo (l ) As Variant
End Sub

button.

Private Sub Comman d l_Clic k ( )


If Tr im$( t x tNewValue .Te xt) = ~" Then Ex i t Sub
intlndex = intl ndex + 1
De mo ( i nt l nde x ) = t xtNe wValue. Te x t ' Let

Labe13.Caption = i nt l n de x
t xtNewValue.Text
End Sub

" .

~(&r " "'*


pot; ( ve u'

,_ .. -
1rJe" vv6c.o V 2

) IrcIe. 12__
1" n:px{:o rou!ndex """ ...
I~-]I

. 3.5. .

Let Demo ,

--
, vntDemo, :

- 42
Proper~ y Le t Demo (In dx As Intege r , As Vari an t )
Indx > UBou nd (vntDemo ) The n

ReD im Pre serve vntDemo ( Indx)


End Ifvnt Demo( I ndx) =
End Prope rty

button.
Privat e Sub -C i c k ( )
If Tr i m$ ( txt NewKey .Text ) = n. Then Ex i t Sub
, Get 1 0

Lab el4.Caption = Demo(Cl nt (txt Ne wKey. Text))


End Sub

Get Demo ,
vntDemo:
Pr opert y Get Demo ( I ndx As I n teger) As Variant
If Indx > UBound (vntDe mo ) Or I ndx < 1 The n
Demo "Error"
El s e
Demo ntD emo( I n dx )

End I f
End Pr operty

Trim$ Visual Basic m '


.

aJ) aD~ naDaDw


, ,
.
. Visual Basic - .
Optional ParamArray. Optional,
, :

, ~ aOX l ReturnTwice l 00~K6 a~6

Ret urnVa lue ReturnTwice () ' E ~ o l Null.


Re t urnValue = ReturnTw ice (2 ) , E ~ ~ 4.

, O ~ . IsMissing 6 Xl

Func t i o n ReturnTwi c e (Op t i onal )

I f I s Mi s sing (A ) The n
0 Nu l l.
Re turnTwi ce =
El s e
,
Ret u r nTwic e = * 2
End I f
End Fun c t ion

--
43
Optional Variant Visual Basic 4.0,
. ParamArray,
, :

Di m As Va r i an t , As Variant
Dim i ntSurn As Intege r

Sub Sum ( ParamAr r a y i n t Num(


For Each IntNum
= +

Next
Int Sum =

End Sub

Private Sub Command-Click ()


Surn 3 . 6, 8 . 10
Msg Box CStr( IntSum )
End Sub

Sum
ParamArray. For Each ,.. Next
.

Ti1U l JI
( . 2.3)

main (
C
DOS main).
standard modle . , ,
, " " Command$
Visual Basic.
Visual Basic VD. EXE :

VD C: \QVD \ SAMP LES \FIN l \ Empo r i k. Ma k

main , :

Sub Mai n ( )

file$ = Command$

End Sub

file$ . ,
main ( End), .

[. vt"'UA I BA", tC

' ' Visual BasIc,


, .

--
....
Ap~

Visual Basic. :
Str$
Slr$ .
VaI:
% ~ 23
St$ - Str$(T %)
% ~ Val( St$ ) + 12 0 0

Inslr, InstrB
Instr

InstrB byte. :

Target$ = ~Au v~ a~ 1K N

Searchl$ " "

Se a r ch 2$ " a "

Sear ch3$ "Vi sua l"

= I n St r ( Ta r get $, Se a r chl$) 0 6
v = InStr(Ta r get$ , Search2$} 0 16
= InSt r ( Ta r g e t $, Search3$} 0

Len, Lenb
Len . LenB
byte. , , resul11
28 :

String l = "

resultl = l e n ( s t ring l )

Left, LeftB, Mid, MidB, Righl, RightB


. left
, Mid ,
, Righl .
, byte.
:

strinql " a l l K 6"

result l Left ( s t r i ng l, 4) \ . " "

result2 Mid (s tringl , 6, 4) " . " "

r esul t 3 Right ( s t r i n g l , 6 ) " . . " . "

Space, Slring
.
, . ,
, Space 20 , Slring

--
ASCII 45, 20 :

45
re su l t1 = Space (20 )
result2 = St ring( 20,45 )

Lcase, Ucase
.

TrIm, L!rIm, R!rim



. Trim .

Format
u Format u .
:

Format ( expression [, forrnat J )

u lormat expression . nou


u u nou lorma!.

. .

# . .

- + $ () .

Visual Basic nou


lorma! (""). nou u , u
.

'

G,ner_1Number .

Currency 10 . .

Percent 100 (%) .


Scientific (s c i entfic ) .

Long _, og _, sysl,m selMgs (Cntrol Pane ~ .

M'dium _, dd-mmm-yy ( . . 03--93) . syst,m


settings .

ShM -, Shon _, syst, msettings .


Lang Tim, sysl,msettings .
Medium Time , " " " ", "hh:mm /" ,

Shon Tim, , hh:mm .

Dim MyTi me, MyDate , MyStr


MyTime 1 17 :04 : 2 31

--
MyDate = IJanua ry 27, 19931

0 46
E~ ~ long time .
My St r = Format (Time, "Long Time" )

E~ ~ long dat e .
MyStr Fo rmat(Dat e , "Long Date" )

MySt r Fo rma t( My Ti me, "h : m: s " ) E ~ ~ "17 : 4 : 23".


MyStr Format (MyTime, "hh:mm: ss "') 'E~ ~ "05: 0 4 : 2 3 " .

\ "Wed.nesday, \ Jan 27 19 9 3 "' .


MyStr = Format( My Date , "d ddd, mmm d " )

\ x ~ f o rmat , ~ ~ o~ ~K

\ n St r $.
MySt r = Format (2 5 ) , . . , "2 5''.


MySt r Format( 5 45 9. 4, " , . 00" ) 1.0 1. "5 ,459 . 40".
MySt r Format( 3 3 4. 9, . 00 " ) E1 ~ "3 3 4. 9 0" .
MyStr Fo rmat (5 , "0.00% ") E~1. '500.00 %'.

MyStr Format ( "HELLO"' , " < "') E~ 1. "hello"' .


MyStr Fo rmat( "Th i s i s i t ", ">" ) E~ 1 "TH1S 1S " .

" "
Visual Basic . .

Date, Tme , Now


.
.
;

res u lt1 Dat e ~ ~ "2 4 / 9 / 9 7"


r esult2 Time ~ ~ "2 : 10 :44 "
result3 Now ~~ "24 /9 /97 2 : 10 :44 "

Day, Month, WeekDay, Year, Hour, Minute, Second


. [
:

, n Da t e 1.~ 24 /9 /9 7
, K ~ n Time ~1 2 : 10 : 4 4

result1 Day (Dat e ) ~~ 24


r e s ult 2 Mo nth( Da t e) 1 ~ 9
r es ult3 Week Day( Dat e) 1. ~ 4,

r e s ult 4 Year( Da t e) ~ ~ 1997


r e sult5 Hour (Time) ~ ~ 2
re s ult6 Minut e(Time) 1. ~ 10
r esult 7 Se c ond(T i me) ~ ~ 44

DaleSerial, TmeSerial
DateSerial ,

--
47
. TmeSerial.

l ( 1)
Visual Basic ,
, :

m .

Sin .

. m .

e ( ) .

Log .

Sqr .

Randomize .

Rnd .

nvv
MsgBox, '
. ,
, .
:

sg (rmt buttons J [, t itle])

prompt
title .
, prompt chr(1 3) & chr(1) (vbCrLf)
, :

Ms g Bo x ~ L i ne l n & v bCrLf & nLi n e2 " & vbCrLf & ~ L ine3n

buttons
, . defau~ ,
:

1 C.ncel'
2 b , Retr Ignore.
3 Yes, CanceI.
4 Yes ,
5 Retr C.ncel'

--
:

48

1 .

2 Cance1.
3 Abort.
4 Retry.
5 I,.

Yes.
7 .

,
l $ :

I nputBox$ ( prompt [, t itle J [, defau l t J [, ] [ , ] )

prompt
ttl e . defau ~ ,
. ,
3.6.
dim r c
rc = nut $( ~ aaa . & _
vbCrLf & v bCrL f & UMn ~ 10 a ." , _
" " , " . " , , )

13
Io:/;J rpooy:rte cme
.

Mro( t ree (.

. 3.6. l t $ .

tt p r r l>oEveJIt s
( ) ,
,
,
OoEvents. 32-b!
, Windows 95 "preemtive multitasking".
16-b! Window$ 3 .,
OoEvent$ , ""
.
standard
.

Dim , OpenForms
Fo r = 1 1 5 0 00 00
Ope nForms = DoEvents \ . 1. 1 .

--
Next

"9
.
Basic, 11 ...Then ... EIse, Do For,
Basic. , Visual Basic :

11 ... Then
:

! Conditi on The n s t a t ement

! Condit ion The n


[ s t a teme n ts ]
End If

Condition , True
False . , condition True, Visual
Basic Then. ,
. condition False
, ! ... Then ... Else:

If Conditi onl Then


[ s t a tements l ]
Elself cond i t ion2 t he n
[state ments 2 ]
Else
[statements3 ]
End If

Elself. . ,
4 command button controls
. event Click, :

Sub Command1-Click (Index As Integer)


! Index = Then

Elself Index 1 Then

El s el f I nde x 2 Then

Else

End I f
End Sub

, myDate:
Su b FixDa t e()
oim myDa t e

--
myDate - # 2 /13 / 95#

50
If my Da te < Now Then myDat e = Now
End Sub

Elself ,
SelecI Case. , , 1I
boolean. :

If (age < 16 And sex = "") Or ( a g e > 14 And s ex = "F") Then


Bl - 10
E1se
Bl

End If

1 = (age < 1 6 And sex = ~M " ) Or ( a g e > 14 And sex = ~F ") * 10

Select Case
Visual Basic 1I ... Then ... Elself, Select Case,
. :

Sele c t Case test e x p ress ion


Cas e expres si on l
[ s t atements1 ]
Ca se expre s s i on2
[ s t a t e men ts2]
Ca se El se
[stat eme nt s 3 ]
End Se lect


Case. ,
Case Else. , :

Sub CommandL-Clic k ( I ndex As Inte g e r)


Se lect Case I ndex
Case

Case 1

Case 2

Case E1s e

End Se 1e ct
End Sub



. Visual Basic Do ... FO ... Next.

--
Goto, -

51
, Do ... .
. l Do :
00
[ s t a t e me nt s]
Lo o p

.
target$ '
slrinS. , GoTo:
Funct i on CountSt ring ( s tr i n $ , t arge t $ )
positi on % = 1
l a b:
fi nd% = I nStr (po sition, s t r i n, t arget )
If f ind% The n
po s it i on = InStr(position. st r i n, t arget) + 1
CSt ring% = CStri ng % + 1
GoTo l a b
End I f
CountSt r ing CSt r i ng %
End Func t ion

. ...
:

Functi on CountSt ring ( s t rin $ , t a rget$ )


posit ion% = 1
00
fi nd% = InStr (po s i tion, s t r i n, targe t )
I f f i nd% = The n Exit
pos ition I nStr( po s i tion, str in, target ) + 1
CS t r i ng % = CSt r i ng % + 1
Loop
CountSt ring = CSt ring %
End Function

... While :

00 While condition
( s t a t eme nts ]
Loop

condtion (True),
m False () . :

Function Count St r ing ( s t r i n$, target$ )


posit ion % = 1
Whi le I nStr( p os i ti on, st rin, target )
p os ition I n St r( p o s i t i o n , s trin, t arget) + 1

--
CSt ring% = CString % + 1

52
Loop
CountStr ing = CString%
End Function

00 ... L,
:

[statements)
Loo p While condition

False Tre .

j9 _~ _ poppg 9
Unt i l condi t ion
[statements) [ s t a t e me nt s ]
Loop Loop Until condition

For ... Next, :

Fo r co unter = s t a rt end [Step in crement ]


[ s t a t e me nt s ]
Next [counter]

counter ( ) , end, increment.


, .
, counter end incre-
ment. For . ,
$ $ :

Function Del imite r ( $, $)


Dim k As Integer, i As Integer
I f Tr i m$( A$) = ~" Then Exi t Funct i on
Fo r i =1 Le n (A$ )
I f Mid $ ( A$, , 1) - BS Then k - k + 1
Next
De l im i ter = k + 1
End Function

For ... Next For Each ... Next,


(collection) .
:

For Each e lement 1 g roup


[ s t a t e rne nt s]
Next [elemen t ]


text, :

Found = False
For Each MyObject 1 MyCollection

--
If My Ob j e c t. Te x t = ~ H l lo " Then

53
Found "'" True
Exit For
End !

Next

M~oo (Mettods)

VT , (forms) controls,
controls (properties)
events.
control. , :

[Ob jec t . ) Method [Farameters]

Object (name) .
object form , Cls:
[Fo rm. ] Cls

. , Form
. :

Cl s

. Hide ,
:

[ . ] Hi de

Show,
:

[ fo rm. ]Show [s tyle]

style , modeless 1 modal.


, .
modal
modeless. modeless,
Show, modal. m , Visual Basic
. ,
. ,
, , :
Sub Commandl_Click ()
Di rn Msg
Hide
n ~ ~ ~

Msg "'" n
MsgBOX Msg
Show
End Sub

controls SelFocus :

--
object.SetFocus

54
control events, !
.

() (

Basic,
,
" " . Visual Basic Quick
Basic , ,
, , , con-
trol .
Basic , (sequential), (random)
(binary) . ,
, random disk,
.
. (records) .
25 24. ,
, , byte-by-byte.
, Visual Basic :

Open, , ! # , ! # , Wroe # , pS , Close


Type ... EndType, Open, ! # , Len, Close, Get #
Open, Get # , ! # , Close, Seek, Input$

Open, :

pathname For mode [Access access ] As [ #]file number [Le n=recleng t h]

pat!lname , made
Append, Binary, ',
Outpul Random. access
(Read), (Wri'e) (Read WrIte)_ filenumber
FreeFiIe. , Len
random '
. pa'hname ,
Append, Binary, Random mode.
, Print # ' .

Ope n ~ T ES TF I LEn For Out put As t 1 V10 .


1 1,
Pr i nt "Thi s is a t est " .

Print 11, 1110 .


Print 11, "e " ; .... ; "Worl d" s t ring s .
Print ' 1, Spc ( 5 ) ; "5 l e a ding spaces 5 .

Pr i nt # 1, Tab(1 0) ; ' " 10.

Dim MyBool , My Dat e , MyNull

--
55
MyBoo l = Fa lse : MyDate = t Februa ry 12 , 19 69 1 : MyNu l l Null

Print #" 1, 01 Bo 01ean 1.


Print #1, MyDate dat e 1. "
Pri nt #1, My Nul l 1. nu ll 1."

Clo s e ' 1 < 1. .

, ' :

Dim Fi l e Nurnber
FileNumber = Fr e eF i 1 e
Ope n ~T EST.DAT" For Out put As iF ileNurnber
Wri t e iFi1eNumber, ~Au 1. 1.
Cl ose t Fi1eNumbe r

! #
TESTFILE,
Wri!e # , ' ,
("Hello", 354):
Dim MyString, MyNumber
Open ~ TE S T F I LE For I nput As ' 1
00 While Not EOF (1 )
I nput #1 , MySt ring, My Number
Print MySt r i ng, MyNumber
Lo

Close # 1

Line ! # ,
Chr(13) Chr(1 3) + Chr(1) ,
, '
!e tbox control:
Dim Te xt Line
Open ~TESTF ILE " For I np ut As 1 1
\ 1.
0 0 Whi le No t EOF ( 1 )
Line Input 11 , TextLine
Te xt1 . Text = Text1 .Text + Chr$(13) + Ch r $ ( 10 ) + Te xt Line
Lo

Cl ose ' 1

, :

Text 1.Text = Input$ (LOF(.1 ) , , 1)

random ,
.
, :
Priv a t e Type Or g anize r

--
SurName As String * 30

56
Name As String * 2 0
Address As String * 40
Telephone As String * 10
Credit As Long
Charge As Long
End Type

. ,
indexlextboxes conlrols COXO
buttons .

wp;g, , . ./. . ~ !l


..,
I.

..,
11

,

llO


,--J 11 ,,"""

. 3.7. .

co ' F le .fl" lextboxes con-


Irols. LaslRecord
Recnum . Seek #
, , , l # :

Private Sub Commandl _Click( )


, ~~ ~ o Or g ani z e r
Di m Data lnput As Or g a n i ze r
Di m Re c Le ng t h As Long
Dim FileNum As I nt e g e r
Di m DBFile As String

\ textboxes contro ls
Call TakeValues(Data Input)
RecLength = Len( Data lnput)
Fi leNum = FreeFile: DBFi le ~DBFi le. fi l H

'

DBFi l e For Random As FileNum Len RecLength

,
LastRecord = LOF(Fi leNum ) \ Len(DataInput)
Recnum = LastRecord + 1

--
, K ~

57

- -- - -- - -- - ""-'-- - - - -- - - - - - - - - - - - - - - -
\ .
Seek #FileNum, Recnum
Put #FileNum, , Da t alnpu t
Close #Fil eNum

For Index = 5: Te x t l ( I nd e x ) . Te xt ": Next


Textl (Q ) .SetFocus

End Sub

SurName.
, ,
, SurName ,
, tetb oxes controls :
Private Sub Command2_Click()
Di m SurnameToLook As Str ing
Dim DBFi le As Stri ng
Dim Datalnput As Organizer
Dim RecLength As Lo ng
Dim Fi leNum As I nt e g e r

Call TakeValues(Datalnput)
RecLength = Len(Datalnput )
Fi l eNum = FreeFi le: DBFile = "DBFile. fil"

SurnameToLook = rim(nut (" . ", "

" ))
I f SurnameTo Look = "" Then Ex it Sub

Open DBFi le For Random As Fi leNum Le n = Rec Length


Last Record = LOF(Fi leNum) \ Len (Datalnput)

\ l.l.Q l.
Fo r Recnum = La s t Re c ord 1 Step - 1
Seek #FileNum, Recnum
Get #FileNum, , Datalnput
I f Trim$ ( UCase$ (SurnameTo Look
UCa s e ( Trim$ (Da t a l nput . Su r Name Then
Te x t l (O ). Te x t Data lnput. SurName
Textl(l).Text Da t al nput. Name
Textl(2).Text Datalnput .Address
Te xt1(3) .Text Data lnput .Telephone
Text1(4) .Text Da t a lnput . Cr e d i t
Text 1 ( S) . Text Datalnput .Charge
End I f

Next Recnum
Close #F ileNum

If Te xtl(Q).Text = " Then


MsgBo x " \\ & SurnameToLook, vbOKOnly, " "

--
58
End If
End Sub

j OrganIzer,
textboxes controls:
Private Sub TakeValues(Datalnput As Organizer )
Datalnput.S urName = Textl(Q).Text
Datalnput .Name = Textl(l) .Text
Datalnput.Address = Textl(2) .Text
Datalnput .Telephone = Text l(3).Text
Datalnput.Credit Val(Textl(4).Text)
Datalnput.Charge = Val(Textl (S) .Text)
End Sub

, , , , byte-by-byte.
, ,
. , Fl e Co py ,
CopyFile . ,
30000 bytes source$ dest$. j ,
Lof, source$, k, ,
30000 bytes i bytes
:

Sub CopyFile (source$, dest$)


Dim k As Long, 1 As Long
Dim il As Integer, i2 As Integer
Dim i As Integer , j As Integer

, source$
If Dir$(source$ ) = "U Then Exit Sub
, dest$ u KOl

If Dir$ ( de s t $) Then Kill dest$


i l = FreeFile: i2 = FreeFile

\
Open source$ For Binary As #il
Open dest$ For Binary As #i2

v 30000 bytes

1 Lof(#il )
k ~ 1 \ j ~ 1 Mod 30000
30000:
For i = 1 k
bb$ ~ Space$(30000)
Get #il , , bb$: Put #i2 , , bb$
Next
, v Vlo Kl

I f j Then
bb$ = Space$(j): Get #il, , bb$

--
Put #i2, , bb$

59
End !
Cl o s e # i l , i2

End Sub

(DebuggLTIg)


Visual Basic .
, (Single Procedure Step) ,
' (Breakpoints),
.
. '
Debug , toolbar,
.

. 3.8. debugging toolbar.

(modes) ,
design time, , ru time, ,

break, , .
Break toolbar CTRL + BREAK.
(caption bar) Visual Basic.
, debug:

d.bugging

Toggl. Br.akpoint , Visual Basic -


. br.akmad .
Quick Watch , C o
break mode.
Call Slack break mode,
, " .

Step l .

Step " , -
.

Run ""
design, Continue, Break
End
time. break mode
. breakpoint, " "
F8, design.
, , , ,
break mode.

--
60
M'i!jI\ .ll
I (~ner .. ) J
IInth$ (5} .. "!l.Y~: !lnth$ (6) .. ~J un " : IInt h $ ('7) .. "Ju. ~ : .!IntM " ...
IInth $ (9 } .. "Sep~: !l.nth$ (10) .. " OC:t~ : !lnth$ ( 1 1 ) .. "No ~: !lnth$ ( 12

tt xt r a ct$(Tr i ltl!j(I1ecr y p t ( "CO",p_ s e t t lnqs", "CO",p_pas s ")! , " , " , 2}


Lo ad MOUt : Mou !:. .. " 1" : ab out. Sho u 1
I t "e b_o n .. 1 Then [ !: Sub
It
_. ." '41..'--. .' ..0'
s tartup node $ " Tr1 1D$ (Read I ni$ ( '"Node z " , "S t ar tup "l )
I t star~up no de $ " ~ " The n star tup node $ .. " Z e us ~: Ca l l IIr iteIn i
c u r r e Dt /i,,$ .. s t art u p node $ : tl 1-"eleCted .. - 1
I~ _va Read n "COlll_:;t t i llQ"S - , -;l1_ c ont - ) J Then sh_all _ Shv : ...=J
,.. ~ ill

. 3.9. F8 breakpoint l .

break mode, CRTL + G


' (immediate window)
. , ,
:

Pr int pro ject ? p ro ject

.

. , ' , ,
.
, Add Watch, '
break mode.
Quick Watch .
, "Shift + F9",
, Instant Watch, .

ax (p ~
' , .
. m . , '
,
. Visual Basic QuickBasic
, . Error,
, ,
, , .
, , .
Resume, ; :

Resume () ' .

Resume Next ' .

Resume line (I.bel) line, m


. oui .
GoTo line.

--
61
, Err m m
, Error Error$ .
. l _open [ ,
, m m
Err :

Function file-open ( f $, ) As Integer


Erro r GoTo telos
i = FreeFile
Select Case

Case 1
apen f$ Fo r Output As ~i

Case 2
Open f$ For Input As #i
Case 3
f$ For Ra ndom As #i
Case 4
f$ Fo r Binary As #i
Case 5
Open f $ Fo r Append As #i
Case Else
i=O
En d Se!ect
file-ope n = i
Exit Function
telos:
i = - Err: Exit Funct ion
End Function

' 1 32767.
m Visual easic, ; Err.
Err = n

, Error ,
:

Sub Form-Cl ick ()


Dim Msg, UserE rror
Error GoTo Er r orHa n d l e r
Msg = " l "
Msg = Msg & " mes sage. "
UserEr ro r = InputBox (Msg )
Er ror Us erError ' l Ql

Exit Su b

ErrorHandler:
Msg " l"

Msg Msg & Er r & " Eivl :" & vbCrLf


Msg Msg & " " " " & Error (Err) & """"

-- 62
MsgBox Msg , 1

Resume Ne x t
End Sub

Asse rts
Assert i Debug, i
oj i debug mode,
i . :

De b ug. As s ert (bo olean e xp re s sion )

i ,
False, .
, i , j CustName
"George":
De b ug . As s ert Trim (Cu stName ) <> uGe orge"

[ - n

Monte Carlo
Monte Cario [ i [ oj
i i, ..
, i .
i OOKj:

[vCidxl
Monte Carlo, :
,.--- - ---,
I=~/N
, [0,1].
Rnd, i TUXaio .
TUXaio [Iowerbound, upperbound] :
Int( ( upperbound - lowe rbound + 1 ) * Rnd + lowe rbound)

, i 600 [ (
i j ) :

--
63
Dim i , ,

Fo r i = 1 600
~ Rnd (l )
= + Sqr{l - 2 )
Next
~ / 600

MsgBox " ~ " &

0,7867323968301 69,
, /4 , = 3,14""


InsertChar sChar ' sTarget iPos.
Sub I n s e r t Ch a r {sTarget As String, sChar As String, iPos As Integer)
If Len (sChar ) <> 1 Or Abs (iPos) >= Len(s Target) Then Exit Sub
Mid$ ( s Ta r g e t, Abs ( iP o s ) , 1) = sChar
End Sub


, ab byle
, ReDim.
Function I s Ar r a y Emp t y ( a b ( ) As Byte ) As Boolean
Dim v As Variant
Error Resume Next

v = ab(LBound(ab) )
IsArrayEmpty = (Err <> )

End Function


VIsual 8asic,
, False .

Function Kill(ParamArray vF iles( ) As Var iant) As Boolean


Dim v As Variant
Error Resume Next

For Each v vFi les


VBA.Ki l l v
Next
Kill = (Err )

End Function

--
6<1

FmtStr Visual
Basic. iWidl h,
, fRighl ( False),
.

Funct i on Frnt St r( iSt ring As St r ing , i Wi dt h As Integer,


Opt ional f Righ t As Variant ) As St ring
Lo c al Error Re sume Next

If i Wi dt h <= Then Exit Functi on

If IsM i ssing (fRight) Then fRight = Tr ue


If f Ri g ht Then
FmtStr Left $ (iSt r i ng & Sp a c e $( iWidth ) , iWidth)
El se
FmtStr Ri g ht$ (S pace $ (iWidth ) & i String. i Wi dt h )
End I f
End Fun c tion

conlrols
controls
. Command butlons controls. :
Privat e Su b Command l-Cl i ck { Index As I ntege r )
GetCon trols Comrnandl ( )
End Sub

GelConlrols Variant.
Sub GetCont rols ( CArray As Variant )
o i m C As Con t r o l
For Each C n CAr r ay
MsgB ox C. lnde x
Next
End Sub

controls LBound, UBound Count.


, .
Load .

Su b Cente r Form ( frmIN As Form)


Dim iTop. i Left As I nte g e r
! f rmI N. Wi ndowSt a t e <> Then Ex it Sub

i Top = ( Sc r e e n.He i ght - frm I N. He i g ht ) \ 2


i Le f t = (S creen . Wi dth - frmIN.Widt h) \ 2
I f i Top And iLe f t The n frmIN.Mo v e iLeft , iTop
End Sub

--
65
bitwise

Visual Basic bitwise , macros HIBYfE,
LO , HIWORD LOWORD, C
Iong Integer. LO high-order low-order byte
, HIWORD LOWORD long Integer.
.
wparam ,
long Integer.
Fun ct i on ge thilobyte (wparam As I nte g e r . LOBYTE As Inte ge r ,
As I n teg e r )
\ 1 ~o LOBYTE wPa ram
LOBYTE :::: wParam An d &HFF&
, iVQl wParam:
= wPa ram \ &0 0 And &HFF&
g ethi l o b yte = 1
End Funct i on

Functi on g eth i l o word ( lparam As Long, LOWORD As Long, HIWORD As Long )


\ 1 LOWQRD o f the l Pa ram
LOWRD = lPar arn And &HFFFF &
\ a 1 HIWORD lParam:
HIWORD = lParam \ &HI000 Q And &HFFFF&
get h ilowo rd = 1
End Functi on

Pr ivate Sub Commandl _ Cl ick ()


Dim wPa ram As I n t e g er
Dim LOBYTE As Int e ger
Dim As I nt e ger
\ 1 wPa r am
wPararn = & 7 FF

ret = get h i lob yt e (wPa r am, LOBYTE, )

End Sub

Private Sub Command2_ Cl ick ()


Di m l Pararn As Long
Dirn LOWORD As Lon g
im HIWORD As Long

\ 1 lPararn
lPararn = &H7777FFFF
r et = geth iloword (lPa r ~ LOWORD, HIWORD)
End Sub

--
66
Cvi Mki$
Visual Basic Mki$ Cvi%
Basic. Mki$
:

Function Mk i $(i%)
temp l& = i %
If templ & < The n
templ & = t e rnp l& + 65536
End r f
b yte1 % = t emp 1& \ 25 6
byte 2% = templ & Mod 256
C1$ = Ch r $ ( b y t e 1%)
C2 $ = Ch r $ ( b yte2% )
Mki$ = C2 $ + C1$
End Func t i on

Gvi ,
Mki$:
Function Cvi%(i $)
b ytes1 $ = Left$ ( i$ , 1)
byt es2$ = Mid$ ( i $ , 2 , 1)
t empl& = As c(bytes 2$) * 2 56& + As c( byte sl $)
I f t empl & > 32 767 Then
temp l & = temp l& - 65 5 36
End If
Cvi% = templ&
End Funct i on

Extract
a$ .
b$
Extract G. , a$ = "dem01\dem02\dem03\dem04"
b$="\" , , G=3, "dem03".
Func t i on Extract$( a$ , b$ , C)
Dim i As Long, k As I nt eger, m As Long
temp $ = Trim$(a $): rf t e mp$ = ~N Or C < 1 Then Ex i t Func t i on
Do
i = InSt r(temp$, b$ )
I f i Then
k = k + 1
If k = C The n
m = InStr(t e mp$, b$ )
I f m Then
Extract$ Left$(temp$ , i - 1): Exit

El s e

--
Extract$ temp$ : Exit

67
End If
End I f
If i + 1 > Le n( t e mp $ ) Then E it 00
temp$ = Mid$ ( temp $, i + 1)
El s e
k = k + 1
I f k = C Then Etract$ ternp $
E i t 00
End If
Lo

End Function

Delimiter .

Rinstr
b$ aS.
' .

Fun c t i o n Rinstr(a$ , b$ )
Oi rn i As Long
For i = Le n (a$ ) 1 Step -1
C$ = Mi d S ( a$ , ., 1) + C$
If InS tr (C$ , b$ ) The n
r i n s tr = i: E i t Func t i o n
End If
Net

En d Func t i o n


j}/JUTIva Replace first$ a$
afte$ :

Su b Replace{a$, fi rst$ , a fter$)


For i = 1 Len(a$ )
d$ = Mi d $ (a$, i, 1)
I f UCa s e $( d$ ) = UCase$ (first$ ) Th e n
C$ C$ + afte r$
El s e
C$ C$ + d$
End If
Ne t

a$ - C$
End Sub

Strdel a$:
Sub Strdel (a $, 1)
For i = 1 Len (a$)
d $ = Mid$(a$ , ., 1)

--
68
If i <> 1 The n C$ C$ + d$
Next
a$ - C$
End Sub

Stripchar b$ a$.
aS:
Sub St ripchar(a$ , b$ , 1 As Integer)
1 -
For i = 1 Len(a$)
Fi nd% = : m$ = Mid$ (a$. ., 1)
Fo r j = 1 Len(b$)
d$ - Mid$ (b$ , j, 1)
! UCase$(m$) = UCase $(d$) Then Find% 1: Exit For
Ne xt
If Find% = Then
C$ = C$ + m$
1 = 1 + 1
End If
Next
a$ = C$
End Sub

Striprange a$
ASCII start end_. b a$:
Sub St r ip rang e (a $, s tart As Integer , end- As I nt e ger, b As I nteger )
b =

Fo r i = 1 Len ( a$ )
d$ = Mi d $( a $, i, 1)
I f As c( d$ ) < start Or As c( d $) > e nd- Then
C$=C$+d$
Else
b = b + 1
End I f
Next
a$ = C$
End Sub


Windows
. . AppRunning ,
. ,
. ,
Visual 8asic, ( ) ,
Prevlnstance, :

--
69
Sub AppRunning ()
Dim sMs g As St ring
I f App.PrevIns t a nce The n
SMsg = " " & App oEXEName & " x ~! "
Ms g Box s Msg , vbCr i t i c a l
End
End I f
End Sub

GetAPPPath , '
, "\" . Path .
:

Fun ctio n GetAPPP ath () As St r i ng


Di m s Temp As St r i ng
s Temp = App. Pa th
If Rig ht$ (s Temp , 1) <> " \ " Then s Temp sTemp + " \ "
GetAPPPath = sTemp
End Fun c t ion


label textbox

control. LongFileNameFix
,
. , , , label
40 , LongFileNameFix(File, 40).
:

Fun c t i o n Lo ng Fi l e Name Fi x ( I n c omrni ng As


Stri ng , Max As Int e g e r ) As St r ing
Di m i As Integer, Lbl Le n As I ntege r , Stri ng Len As I nt e g er
Dim TempSt ring As String

TempS t r i ng = Incommi ng
LblLen = Max
I f Len(Temp St r i ng) <= LblLen Then
Long FileNameFix = Temp String
Exit Fu nc t i o n
End If
LblLen = LblLen - 6
Fo r i = Le n( TempSt r i ng ) - Lbl Len Le n ( TempString )
If Mi d $ ( Te rnp St r i ng , i, 1 ) = " \ " Th e n Ex it For
Next
LongFi l eName Fi x = Le ft $ ( Te mpS tr ing , 3 ) +
"0 00" + Right$ ( Temp St r i n g , Le n ( Temp St r i ng ) - (1 - 1
End Funct i o n

--
70


, (
recursive).
Funct i on Le nLong e stWo r d ( ByVa l s rc As St r ing ) As Integer
Di m i As Integer. j As Integ er
i = InStr (src, \\ \\ )
If i > The n
j = LenLongestWord(Mid$ ( src, i + 1
! j > i - 1 Then LenLon ge stWord j El s e LenLongestWord i - 1
Else
Le n LongestWord Len(src)
End If
End Func ti on


,
IsValidPath . , ,
vbDirectory vbNormal, :
Fu ncti on I sValidPath ( s t rPath As Str ing ) As Bo o lean
IsValidPath = Di r (st r Pat h. vbDirectory) <> \\>'

End Fun c t i o n


CreateLongDir ,
,
Dir$.
K~oo :

Sub Create LongDir sDr ive As String, sDi r As String )


Dim s Bu i l d As String
While InStr(2, s Dir, " " } > 1
sBui ld = sBuild & Left $( s Di r , InStr( 2 , sD i r , " ' >') - 1)
sD i r = Mid$ (s Di r, I n St r ( 2 , sDir, ", ..
If Dir$ (sDrive & sBuil d, 1 6) = .. ... The n
MkDir sD r ive & s Bu ild
End I f
Wend
En d Sub

Call Cr e a t e Long Di r ( "d : ", "\Test \Te stl \ Lo ng Di r e ct ory Name\ "')


Visual Basic, SaveSetling GeISetling,
Registry Windows.

, .

--
71
PutFonPos~ion Left. , Width Height
. Tag :

Sub PutFormP os it i on (F As Fo rm )
Dim bu f As St ring
bu f = F. Le f t & "," & F.Top & "," & F.Width & "," & F.Height
SaveSetting . EXEName, "Fo rmPo s i t ion" , F. Tag, buf
End Sub

Unload .
GetFo nPos~ion Registry .
Load :

Su b GetFormP os it ion (F As Form )


Di m buf As String
Dirn 1 As Integer, t As !nteger
Dim h As Int e g e r , w As Integer
Dim p os As I nteger
buf = Get Sett ing(App. EXEName , "FormPosition", F. Ta g, "" )
I f bu f = "" Then
K ~
, Regist ry
F.Move ( Screen.Width - F.Width ) \ 2, ( Sc r e e n. He i g ht - F.He ight ) \ 2
El se
, 1 a

p os = I nSt r ( b uf, ", " )


1 = Clnt (Left (buf , 1 : bu f = Mid (buf, pos + 1 )
pos -
po s = InSt r(bu f, " , "}: t
Cl nt ( Le f t {b u f , p o s - 1 )
=
buf = Mid (bu f , pos + 1): pos = I n St r( bu f, "," )
w = Cl nt (Le f t (b u f , pos - 1 : h = Clnt(Mid(buf, p os + 1
M a ~

F.Move 1, t, w, h
End !

End Sub

1) ;

; m .

2) ; .

3) Publc Private; ;
.

4) " " ;
.

5) ;
.

--
72
6) main;

7) Visua/ Basic.

8) ; l
; ; Redim Preserve
Redim; Vissua/ Basic.

9) Visua/ Basic.

10) (structures); .

11) ; Form.

12)
Extrac/.
custom Defmiter

13) Exist
D$.

.1 . = 5 = 3, True/False
:


<
> =
=
*3<+4

2. ;
12, 3C, 2 , Name$, $B, .

3. 1 6.
For ...

4. 1 100.
.

5. (1 ) '
( 10) , .
l l .

6. :

TakeSectio n( istri ng$, t mpl $, tmp 2 $, Opt iona l En d s As Varia nt) As String

--
73
tmp1$ tmp2$.
Ends , tmp2$
.

7. .

8. text box control multiline


. , command butlon InputBox$,
i textbox control.
, 65 i.
.

. 9. ' nivaKG i i
. .
, command butlon , ,
( Print) .

10. CVL L$, i CVI $



Long Integer.

--
7 -4
~!/(,
jd ---'~

MeJu

, command
buttons , Visual Basic
. menus .

/"",nuMIt
:::r"'
~ Menuitem L.te<'IUbaf _ l l
B3~~",
,,--- ~__ 1

~
Separalor t
,"00

. 4.1. menu Visual Basic.

menu bar (caption)


menu titles ( File 4.1.), menus. menu
items. ( New), separators submenu titles,
() . menu item ' menu control
Menu Editor.

MeJ)u EdLtor
Menu Editor design
menu controls
. , Menu d t r

--
Tools Menu Editor button toolbar.

75

~
,-
Cgxn- ! w

'''' j......,ilelleo


J:ieteoo:e>4!D:

r"""",
r-
P .E.rIbIed

II~ 1 .!! ~,! _, 'I ~


-
'-_~~.~
P" ~d>I!
IIN~I
~
J

~'I!lI'"ldov<L*,

..
"'-
" "Wer .
....S-1M..
- . .. ,. J
........ -...
-- &.Cdo:.
-
-, ..:J

. 4.2. Menu Design.

menu control, Name CaptIon,


, control, ,
control.
menu controls :
.
f!j Menu E dto r
toolbar.
@) CaptIon text box menu ttle .
Menu Edto r. (-),
separator bar menu items.
o Nametext box control. menu controls
Name ( menu controls,
) .
(;) menu ( ) .
@ .
8 Next menu control, Insert
menu . , Delete
menu control. Up Down menu controls
, .
GJ , Menu Editor menu con-
trols ,

, menu .
click menu control, Code Window
. ,
, click Visual Basic ,
, menu controI click.
Clck menu control :
Pr i v at e Sub Name-Click{ )

--
End Sub

76
n MeJII CoJItroI
, controls controls ,
, events. menu controls.
, ,
run time ,
menu items.
, design, '
. Index text box
, .
Click .

Pr ivate Sub Narne-Cl ick ( Index As Integer)

End Sub
Index .
menu cantrals menu
submenu.

SubmeJIU5
submenu '
menu menu items.
submenus.

r - - - - - -- - -- - ---,
'
- "
~ Bodd:t>b F F~F Nf FOR MICROSOFT 5
! [ " s_ . , . !!

IMPORTANT- READ
'- ,
CAR~ I#" I. ~;bi"

betwe en you (ei1her < o~ t!m,t:BIJo
individual
identified above. which includes computer 50 a <
oIln:~ elec1ronic documen 1ation I SO FTWA RE PRO
SOFTWAR E PROOUCT, i 10 be bound bythe
EULA, dO in5103ll use the SO FTWAR E PRODUC:
refu nd

SOFTWAR E PRODUCT UCENSE !

. 4.3. submenus.
, Menu d r.

! c~,l m ~~
""" 1- J' """
)ro~: ~ ~: 1(""""")
~,"" ID:~ ~:!o'No<>e J
r Q>o<t.ed P' ~ P' ~ r ~

:!li]:!li] D:Jr!:EJ ~
=, "-',
..
_"'"
<IR.d
~..
" " " " H$Je

-~
J
. . w .d
. ......-&Gr.""
.",,,,,,,.-&fIb
' ;;:;;;:.-&1a.e_ ..:J

--
. 4.4. 4 submenus.

77

menu controls, Name CaptIon,


. Enabled menu conlrol.
menu conlrol ,
:

Me nuname . Enabl ed = False

, menu controi MenuFilename 2, :


Menuname (2 ) .Enabled = False

Checked, check menu ilem,


on/off , 4.5.

. 4.5. checked menu item.

, check
menu ilem, Click conlrol:
Private Sub Menultem-Click ()
Menultem.Checked = Not Me nu ltem.Checked
End Sub

Checked Menu Edilor,


check bo.
menu control,
Visible, run lime :

Menuname.Visib le = Fals e

, menu conlrols, , , 1:
Menuname(l ).Visib le = Fa lse

menu lille , menu ilems '


. Visible Menu Editor,
check .
, , menu lille Menu
bar, Help Menu, Form_Load :

He lpM enu .Cap tion = Chr$ (B ) & He l pMenu .Capt ion

menu , ,

--
(keys) access shortcut. access ' menu

78
L menu item, .
caption command buttons,
(&) .
menu item.
s ho t cut '
function-key control-key, CTRL+F2 CTRL+X.
shotcut, Shotcut combo bo Editar.

>- rneJjU5
menu menu
bar, 4.6.

'81
i _ '*"4.. 1, . g

Ies! U1!OnS
"!:f.orrJ'M: end AutoSI

Q>ed<Box
tlumberSy$!em
Lt$16QX
MuIIpl e-Colum n l.$.1 ;

SoOIBm
Conlrpl&r~

. 4.6. - memu,

- menu PopupMenu :

( fo r m. ] PopupMenu menuname [, flags [ , . ] ] ]

, - menu, flags
menu. , , - menu
.
- menu 4.6.,
4.7., menu.
,
!- ..",.
,........
- ,-
~
'- ~
1-
Iot;Ud...:D ----
"'"'" 10_ 3
.,.... ,- ,- r,.....
~ .!I:iI .!I :::J ~-=.J

----
- ... -

"'""'~
.

---
--VUoDor s,....
~~
- ~ . 800
. ..8 ..

--
. 4.7. l - memu.

79
Click . :

Pr i vat e Sub Fo rrn-Cll c k ()


POpUpMenU mnuCont r o ls
End Sub

PopupMenu, menu ~em


ESC.
Textedit
text bOK control txtEdit. menu
, , text box, menu
~ems ,
. , menu controls ' ,
.
, d~. F Textedit.Bas.
' .

text box

o ~ xl

Pr i vate Sub Form-Load ()


t xtEdit . Move ,
= Scre en. He i ght / 2 - Height / 2
Left = Scre en. Width / 2 - Width / 2
End Sub

event Res i ze a1Q n .

text b ox control 0

n . .

Private Sub Fo rffi-Re si ze ( )


txtEdi t.W idth = Sca! e wi dt h
t x tEdi t.He i g ht = Sca l ehe i g ht
End Sub

\ V1Q text box

Pr i vate Sub mnuBackCo! or Ite rn-Cl ick (I ndex As I nteger)


Se lect Ca s e Index
Ca s e 1
t xt Edit . Ba c kCo l o r RGB(2 55 . . )
Ca se 1 1
txt Edit.Bac kColo r RGB(O. 255, )
Case 2 \
t xtEdit.BackC olor RGB( O. , 255 )
End Select
End Sub

1 n text bo x
a Light Blue

--
80
Sub mnuBlueltem-Cl ick ( I n d ex As I n t e g e r )
If Inde x = Then
txt Ed it.ForeColor RGB( O, 150 , 255)
End If
End Su b

~ t e xt box
Dark Blue.

Private Sub mnuDarkBlue ltem-Cl ick (Index As I n t ege r)


Select Case Index
Ca se
t xtEdit.ForeCo lor RGB(O, 50 , 175)
Case 1
t xtEdit.ForeCo lor RGB(O , , 255)
End Select
End Sub

K~ uv~K menu controls


~oK r un time

Private Sub mnuFileArray_Click ( I n d ex As Integer )


If Index >= Then
Ca llOpenFi l e((mnuFileArray ( Index) .Caption
End If
End Sub

Click Y1Q me nu controls menu

menu b a r.

P r i v ate Sub mnu F il e ltern-C l ick (Index As Integer)


Erro r GoTo errhandler

- Se l e c t Case I n dex
Case
index = , ~ N ew "

K ~K X~K l t e x t box
Kl l caption

t xtEdi t.Text = ~"


Fi lename = ~Untitled"
frmE ditor. Caption = "T ext Ed i t o r : " & Fi lename

Case 1
i ndex = 1, " . .. "
l .

control CMD ialogl,

Q l , l Q l Y1Q i

--
81
CMDi a log l . Filter = ~Al l File s ( *. * )1 *. * Text Fil e s
(* . txt) I*. txt /Ba t c h Fi l es ( *.bat )I *.bat R
CMD i a logl. Filterl nde x = 2
CMDial ogl. Action = 1
Fi lename = CMD i a logl . Fi l e name
Call OpenFi le(F ilename )

Ca s e 2
i ndex = 2. ~ S ave As...
, ~x text box
CMD i a l og l . Fi l te r = ~ All Fi les ( *. *) I*.* ITe xt Fi l e s
( *. t xt ) I*. t xt IBa t c h Fil e s ( *. ba t) I* .bat R
CMD i a l og l . Fi lte r l ndex = 2
CMD i a l og l . Act ion = 2
Filename = CMDialog l .Fil ename
Cal l Cl o s e File(F i l ename)

Case 3
i nde x = 3. ~ Cl o s e R

txtEdi t .Te xt = _
frmEdit o r . Capt i on = - Te xt Edit o r : Untit l ed W
mnuFil e l t ern(3 ). Enable d = Fal s e
Call Cl oseFile( File name)
Case Els e
End Se l ect
errhand ler :
Exit Sub
End Sub

t e xt box cont r o l .

Sub mnuFont Sizes ltern-Cli c k ( I nde x As Int e ger )


Se lect Case I ndex
Case
I ndex = 12

t xtEdit. Font. Size = 12


mnuFo ntSizesl tem (O ).Checke d True
mnuFontS i zes l tem ( l ).Checked Fals

Case 1
I nd ex = 1 24
t xt Edlt. Fon t .S lze = 24
mnuF ontS ize sltem(O).Che c ke d Fa l s e
mnuFontSiz e sl t em(1).Checked Tr ue
End Se l e ct
End Sub
, text box
CMDia l o g lSub mnuFo r e Color l tern-Cl ic k (Index As I n teger)
Select Case Inde x
Ca s eO ' KKK ~O
txtEdit . Fo r e Colo r RGB(255, , )

Case 1 '
txtEd i t . Fore Co l or = RGB(O, 2 5 5, )

Cas e 2
, x ~ K ~ K K ~ submen u
End Sel ect
End Sub

Teted it.Bas . OpenFlle


tet box, CloseFile , tet box ,

, , UpdateMenu controls menu controls,
menu items .

Dim ArrayNum As I nt e g e r
Glob al Filename As String
Cons t MB_YESNO = 4, ~CONQUE S T ION = 32 , D = 7 , MB-DEFBUTTON2 2 56

o~ K~ ~ t e x t box
.
~ x ~ o~ x .

K ~ n UpdateMenu ~ V ~ K
menu i tems menu .

Sub OpenFile (Fi l ename As St r i ng)


Dim F As Int e g e r
If "Te xt Ed i t o r : " + Filenarne frmEd itor. Capt ion Then
Exit Sub
Els e
Error GoTo Er rHandler

F = Fr e e Fi l e
Open Fil enarne Fo r Inpu t As F
frmEdi tor !txtEdit .Text = Input$ (LOF (F ) ,F )
Clo se F
frmEditor !mnuFile lt em(3 ) .Ena bled = True
frmE ditor.Capt ion = "Text Edit o r : " + Filename
Upd at e Menu
Ex it Sub
End If
ErrHandler:
Clo s e F
Msg Box " , OK~ ~ . n , 48 ,
"Te x t Editor"
Exit Sub
End Su b

K ~ t e xt box

--
~ . VB Dir$

8 3
1 .
MsgBox 1 1
(Oerwrite ) .

Sub Close File (F ilename As St r i ng )


Dim F As Integer
Error GoTo CloseEr ror

! Dir (F i l ename) <> ~ " Then


r esponse = MsgBox (~Oe rwr i t e e xisting f ile? ", MB-YESNO +
MB-QUESTION + MB-DEFBUTTON2 )
! respons e = Then Exi t Sub
End !
F = Fr e eFile
Ope n Filename Fo r Out pu t As F
Print #F, f rmEdit or! t xtEdit. Te xt
Close F
Filename = ~Unt itledN
Exit Sub
CloseError:
MsgBox ~BK , 1." , 48
Exit Sub
End Sub
1 1 menu co nt rol s
mnuFileArray. Caption controls 1
1.
c ont r o l 1 separator bar,
1 1 Visible 1 1 True.
1 1 ArrayNum
.
1 110
capt ion 1 0 co nt ro l 1 ,
1 ,
Load 1 0 men u control
mnuFileArray, 1 1 1 Caption 1
Vis i ble 1 1 .

Sub UpdateMenu ()
frmEdito r!mnuFileArray(O ).Vis ible True
ArrayNum = ArrayNum + 1
For i = Ar rayNum - 1

! frmE ditor!mnuFileArray (i ).Caption Fi lenarne Then


ArrayNurn = Arra yNum - 1
Exit Sub
End !

Next i
Loa d frmE dit o r !rnnuFileArray(Ar r ayNurn)
f rrnEd itor!mnuFil eArray(ArrayNum). Capt i on File name
frmEditor!mnuFileArray (Arr a yNurn ).Visible Tr ue
End Sub

1. v v v Vsual Basic;
2. v Submenus;
3. v v v; vrr.
4. v access;

1. ' 3 menu items. ,


CaptIon captIon menu item. ,
BackGround ( Rgb).
, , .

2. ' . text boxes controls


(name ) Surnmame Name, random ,
command button . , menu item,
Caption Surname control. , ' menu
item, random textboxes controls
. ,
, .

--
85 - - - -- - - - - -- ----

Murttpre - DocurneJjt IJjterffCe (MDI)


Multiple - Document interface (D ) (docu-

,
ments) (D form) . Program
Manager File Manager Windows 3..
child, MDI, ,
. child
MD/Child True, D .
Child, , D
desktop Windows ( 5.1 .).

ji ", NolePlId 1!!I1;]~

MOI
work$pace

Minimzed
childwindows

. 5.1 . child .

child, standard,

--
.

87 - - - -- - - - -- - -- - -
poj

D child F 1 , '
multiline textbo controI. D menu , New,
document. :
Privat e Sub New_Click ( )
Dim Ne wDo c As Ne w Fo rml

cn = forms .Count
Lo a d NewDo c
Ne wDoc.Caption ~Formn + Trim ( cn )
NewDoc. Show
End Sub

Count
caption , modal.
NewDoc Form1 (
New Dim, ) events ,
. , ,
' .
F _Resize :

Private Sub Form-Resi ze ( )


Te xtl.Top =

Textl .Left =

Te xt l . Height = Sc aleHe ight


Te xt l .Width = Sca leW idth
End Sub

text bo .
Form1, , :

Fo rml. Text l . =

' , :

Me. Text l . =

, ;
. module :

Publ i c NewDoc( ) As New Forml

, MDIForm_'-oad :

Pr i va t e Sub MD IF or.m-Load ( )
ReD irn NewDoc ( O) As New Forml
Load NewDoc ( O)
NewDoc( O) . Caption = ~ Formo n

Ne wDoc ( ). Show

--
End Sub

88
:

= UBo und ( Ne wDoc ) + 1


Re Dim Presere NewDo c(i) As New Forml
Load NewDo c(i)
NewDo c(i) . Caption = ~Form" + Trim( i)
NewDoc( i) .Show

child , .
. ,
,
Document. . Tet1 _Change tetbox:

Pr ivat e Sub Text l-Change ()


t extl .Tag = -" 1"
End Sub

, Form_Unload.
Tag tetbox , 1, .
Cancel True, :
Privat e Sub Fo rm-Unl oad (Cancel As Int eger)
Di m Msg As String
rf t ext l . Tag = "1 " Then
Msg = " " & Me .Caption & " ~ o~"

Re sp Onse = MsgBox (Ms9, 51 , MDIForrnl. Cap t i on )


Sele c t Case Response
Ca se 7
Cancel Fals e
Case 2
Ca nce l True
Ca s e Else
End Se l ect
End I f
End Sub

Arrange, Documents
, .
:

MD Iform.Arrange arrangement

arrangement .

vbCascade child .

vbTileHorizontal 1 D child .

vbTileVenical 2 KOTOKpuo child .


bang eJ cns 3 D chiJd .

--
89
, vbCascade,
vbTileHorizontal vbArrangelcons MDI child.

.. D No!ePad I!I~ EJ

. 5.2. bCascade D chiId.

,i : iI ! ' Itt ::t\ _ l '


fie ~d ~e.sch Q6:m ~ndow

f 'lfflt!ffi f

. 5.3. vbTileHorizontal D child.

_ l l l:

. 5.4. vbArrangelcDns ch ld .

Restore , MDI child :


Sub Re s t ore ( )
For i = 1 Forms .Count - 1
If Forrns(i ).MDIChild = True Then
Fo rrns (i). WindowState =

--
90
End If
Next
End Sub

Minimized :

Sub Min imized ( )


For i = 1 Forms .Count - 1
I f Forms(i ) .MDIChild = True Then
Fo rms ( i ). Wi ndo wSt ate = 1
End I f
Ne xt
End Sub

Toolbar
toolbar standard ,
. [
bitmap ( control Align, bitmap
standard controls ) , ' buttons .
, custom toolbar control.
, buttons controls,
. , Glick buttons :

Pub lic Sub B-Too l b a r_Clic k (Index As Integer)


Se le ct Case I n de x
Ca s e
Cal l NewDocument
Case 7
Call Cont e nt s_Clic k
Ca s e 8
Call p r inte r_
Ca s e Else
End Se lect
End Sub

--
. 5.5. toolbar Mdi.Vbp.

91
l MDI
MDI,
5.6. MDI ,
PaInt, .
, . ,
. Mdi Child,
bitmap control ( ) . BorderStyle
Control . , bitmap control
.
Resize MDI :

Pr i v a t e Sub MD IF o r rn-Re s i z e()


Center Fo rm Form l
End Sub

Form1 Mdi Child, CenterForm


MDI :
Sub Ce nt e r Fo rm (frm As Fo rm )
frm. Left = (MDIForm l. ScaleWidth - frm. Wi dth ) \ 2
frn. = (MDIForml . ScaleHeight - frm. Height) \ 2
End Sub

, Activate :

Pr ivate Sub Forrn-Activate( )


ZOrde r 1
Refresh
End Su b

Zorder 1, .

--
. 5.6. bitmap MDI.

92

. ro Mu/lip/e - Documenl intertace (DI);
2. D/ D/ chld r r "" ;
3. m MDI.

1. , MDIGhild
.

2. Mdi.Vbp . File
Open menu item, ASGII
textbax control. menu
items. ' ,
.
4 ' ASGII, ,
, .

--
93

Visual Basic

' ,
, . .
, . controis, line shape,
. cantrols ( image)
, (focus), hWnd,
.
, ,
( ), picture control , , printer object.
:

Cls . print object.


! . debug objecI.
Pset (pixel).
! . print object.
Line .

Circle , .

PaintPicture ( . , .WMF, .ICO . . ) ' VKo


Form, PictureBox, Printer.

, (
) ,
Paint , Command1_Click command button,
. , , , object
AutoRedraw True. ( , Visual Basic
controi, ov
, .
,
Visuai Basic.

-
.-
95

, , Left,Width Height controls,


. ,
, , .

x-axi$ ()

y-aKi$
.. CI>Ofd, rate S, sIelfl E x"nple 1![!]3
..
() . : ':.:':" . Fme
: ... 1
"

. 6.1. .


, (0,0). '
, .
, ScaleLeft, ScaIeTop, ScaleWidth ScaleHeight Scale,
defauh .

defauIt twip, 1/20 , , 1,440
.
twips (inch) 567 twips 1 (cm).
, ScaleMode,
:

vbUser (~O) ScaleHeight, ScaleWidth, ScaleLeft ScaleTop .


V bTwips( ~ 1) Twip (Oelaul!).
VbPoinls(~ 2) l (72 nl ) .

VbPixel s (~3)

VbCharaeters(=4)
Pixel ( ) .

/ . ~ 120twips = 240 twips .


Vblnches(= 5) (Inch).
VbM i l lime!ers ( ~6) ( M ll imete r).

VbCentimeters(~ 7) (Centimeler).

, DrawWidth ( pixels) ( )
. 1 (default) 32,767.
, ScaleMode,
, Circle, :
Pri vat e Sub Form-Clic k ( )
, 1 1 ScaleMode .
ScaleMode = Sc ale Mod e + 1 ) Mod 7) + 1

--
, 1 1 , 2.

96
Circle (ScaleWidth / 2, ScaleHeight / 2 ) , 2
End Sub

l,}

, ' Crren
CurrenlY,
' .
:

Circle ( ).

L i .

Print .

Pset

RGB
. :

RGB (re d, green, blue )

255 ( long
integer) .
:
RGB :

RGB(O, , )

RGO(O, , 255)
RGO(O, 255, )
RGB(255, , )

RGB(255, 255, )
RGB(255, 255, 255)

, OBColor, RGB
, 16 OickBasic.
15 :

Forml .BackColor = QBColor ( 15 )

Psel
. :

[object. ] PSe t [Step] ( , ) [, color]

, , Step
Crre n CurrentY
.

--
, color RGB

97
Q8Color. , .
DrawWidth . , DoEvents
, .

Pr ivate Sub Form-Paint ( )


Dr a wWidth= 5

XPos = 300 + Rnd * 4 0 0 0


YPo s = 2 0 0 + Rnd * 4500
PSet (XPos . YPo s ) , QBColor (Rnd * 15 )
Events
Loop

End Sub

Line
. :

[obj ect. ] Line [[St e p] ( 1 , 1 )] - [ St e p]( x 2 , 2 ) , [ ,B[F]]]


Step
CurrentX CurrentY. 1 , 1
, 2, 2 . color
. , ForeColor. 8
, F
,
FillColor.
.
.

Li n e ( 1 0 0 , 2 0 0) - ( 15 0 , 2 50 )

Line (1 0 0 , 2 0 0) - Step ( 5 0, 5 0)

, :

Line ( 5 0 0, 5 0 0 ) - (1 0 0 0, 10 0 0 ) . . BF

... FoIml !!:!

--
. 6.2. Line.

98 - - - - - -- - - -- - - --
:

Priv a t e Sub Form-Clic k ()

Cur r ent X 15 0 0
Cur renty 500

Line -( 3 0 0 0 , 2000 )
Line -(15 0 0 , 2000 )
Line - (15 0 0 , 500 )

End Sub

!
picture control. :

[o bject . ] Point(x,y )

, . objec!,
-1.
.

Priv a te Sub Fo rm-Cl i c k ()


Dim Le ftCo lo r , MidColor , Msg, RightColor

Cl s ' K ~ 6 ~
He i g ht = 3 * 14 4 0 ' L .
Width = 5 1 4 4 0 ' .
Ba ckc olo r = QBColo r ( l ) , backg r oun d .
Fo rec olor = QBColor ( 4 ) f oreground ~6K K1o.

Li ne (, O) - ( Wi d t h / 3 , Height) , , BF \ 1 n 0 1 0.
Forecolor = QBCo! o r ( 1 5 ) , for eground .
Line (Wi dt h / 3 , ) - ( ( Width 3 ) * 2, Heig ht ) , , BF.
LeftColor = int . ) \ 1 0 ~ o .
MidCo lor = Point(Wi dth / 2 , Height / 2 ) \ 1 . 1

Right Co lor = Po int ( Wi dt h , Height) , 1 0 1 .

Ms g ~T o 1 1 ~

Msg Msg & ~ ~ & Le ftCo lo r & " , ~


Msg Msg & 1 ~
Ms g Msg & MidColor & - . ~o -
Msg Msg & 1 1 - & RightColor & - #

MsgBox Msg \ 1 nv

End Sub Eiiiiiiiiiiiiiiiiiiiiiiiiii1

--
. 6.3. .

99
CircIe
, . :

[obj e ct. JCi r cle [Step } ( ) , radiu s [, [co lor} _


[, [start] [, [e nd) , aspect] ] ] ]

Step ,
C rre n CurrentY. (,)
, radius , color
. start end (radians)
, . -2 2. d efau~
. aspect (ratio) . default
1 . ,
FillCoIor FillStyle.

.

Private Sub Form-Clic k ( )

Sca! e Mode : 3 ' p ixels .

\ . . . .

Fil lStyle = : Fi l l Co l or = RGB ( O. , 255)

Circle , 1 0 0) , 50 , RGB( 2 5 5 , . ) \

Ci rcle ( 25 0 , 10 0 ) , 50 , RGB(2 5 5. , }, , , 1 / 3 \ l.

End Sub

.. FoIml I!I~EI

8
. 6.4. .

, Form_Click ,
:

Pr ivat e Sub Form-Clic k ()


Cons t = 3. 1 4

\ 6

Fill Styl e = : Fil1Color = RGB (2 5 5 . , 255 )

Circ1 e ( 15 0 0, 15 0 0 ) , 1 0 00 , - / 2, - / 3 l.

Circ1e ( 3 5 0 0 , 15 00), 1000, , - / 3, - / 2

--
End Sub

100
"i FoIml 1!!IIi1E3

. 6.5. v FoIm_CIick.

PaIntPicture
(. , .WMF, .EMF, .ICO .GIF . . )
' Form, PictureBox, Printer. :

object .PaintPicture p i c t u r e, 1, yl , width1 , he ight1 , 2, 2 , _


width2 , height2 , opcode

l1.
pIcture Picture PicrureBox control.
, 1, 1
width1, height1 2, 2 width2, height2. opcode
.
PaintPicture
bitmap , pIcture controls.
100 picture control:
Fo r i = 10
Fo r j = 10
Forml . PaintP icture pi c F. Picture, j * picF . Width, i * p icF. Height , _
picF .Width, - p i c F. He i g ht
Next j, i

default
. - .

DrawWidth
DrawWidth pixels Line, PSet
Circle. , ,
DrawWidth:

Private Sub Form-C li c k ( )


Dim , i

- - - - - -- - - - - - - - -
--
1
For i 1
12 Step 2
=

=+ 400

DrawWi dth = i
Line (2 0 0 0 , 10 0 + )-(5 0 0 0. 10 0 + )

Next
End Sub

.. ForIIl 1!!I~E3

. 6.6. Form_Click.

DrawStyle
DrawStyle Line
. 6 :

Pr ivate Sub Fo rm-Cl ic k ()


Dirn i ,

For i = 6
DrawSt yle = i
= ( 2 0 0 * i ) + 10 0 0
Line (2 00 0, 10 + ) -(50 0 0 , 10 + )

Next
End Sub

.. Foml I!II!JEJ

. 6.7. Form_Click,

FillGolor FillStyle

--
' , ,

1 02
( Circle Line),
FillStyle
. 7 .
(solid) FillColor, 1 (default)
.
FillStyle,
FillColor. 6.8.
Private Sub Fo rm-Click ()
Di m i .

For i = 7
= ( 80 0 * i )
Fi l lCo lor =RGB( 2 5 5, , )

Fi l l Style =i
Ci r c l e ( 1 0 0 0 + , 1500) , 35 0
Next
End Su b

. 6.8. FiIISIVle.

DrawMode
. 16
, 7 (Xor Pen) animation,
, ,
, .
, .

Pr ivate Sub Form-Click ()


Dim i

Fo r eColor = RGB (255 , , }

Fi l lCo!or = Fo reColor
Fi l l St y le = 2
Dr a wMo de = 7

For i = 1 5 0 0 0 Step 10
Ci r cle ( i, 1500) , 500
Circle (i , 1 5 0 0) , 5 00
DoEv e nt s
Next

--
End Sub

1 03

ScaleLeft, ScaleTop, ScaleWidth ScaleHeight


Scale ' default . ,
, , bitmaps object printer. ScaleLeft ScaleTop
.
(100, 100) .
Sca l e Le ft "" 10 0
Sc aleTo p "" 100

controls ,
Left. , form_CliCk, com-
mand button control .

Pr i vat e Sub f o rm-click ()


Dim

= comma nd l . Le f t
s c a l e l e f t = s c a l e I e f t - 10 0
c ommand l .Left =
End Sub

scaleleft = s c a l e left + 10 0

' .
, ScaleWidth ScaleHeight
. , :

Sca l e Width = 1000


Sc aleHeight = 500

1/1,000 1/500
. command button cantrol,
.

Privat e Sub f orm-c l ic k ()


Dim ,

= commandl . Wi ctt h
sca l ewidth = sca lewi dth - 10 0
command l . Widt h =

= commandl. He i g ht
s cal eh e ight = s c a l e he i g ht - 100
comman dl .He ight =

End Sub

default '

--
, . ScaleWidth

104 - - - - - - - - - - -- ---
ScaleHeight . , :

Sc a l e Height = - 100

.
Scale,
:

[ob ject. ]Scale [(, ) - ( 2 , 2 1 ]

( , 1) ScaleLeft ScaleTop,
ScaleWidth ScaleHeight ' .
, default , Bar char1,
Line.
Pr i va te Sub Form-Pa i nt )

Dim , Ol dFont Si ze

, A ou 0

Wi d t h = 8640: Height = 57 60
\
Move 10 0 , 10 0
\

OldFontS iz e = FontS ize


\ background

BackCo lor = QBCo lo r (7 )


\

Scale ( , 110 ) - ( 130 , )


For = 10 0 10 St e p -10

l Ou 10

Line ( , 1 ) - (2 , )
Cur r e nt y = Cu r r e nt y + 1.5

Print
Line ( Sc a l e Wi dth - 2 , I) -( Sca l eWi dth, )

Curre nt y Curr e nt y + 1.5


Cur r entX = Sca l ew i ctth - 9
Print
Next

\ X lO U bars
Line (10 , 0 )- ( 20, 45 ), RGB(O, , 255 ) , BF
Line (20 , 0 ) - (30 , 55 ) , RGB(255 , , , BF
Line 14 0 , 0 ) - (5 0 , 4 0) , RGB( O, , 255 ) , BF
Line (50 , 0 ) - (60 , 25), RGB(255 , , ), BF
Line (7 0 , 0 ) - (80 , 35) , RGB( O, , 255 ) , BF
Line (8 0 , 0) -(90 , 60) , RGB( 255 , , ), BF
Li ne (1 0 0 , 0)- (110 , 75 ) , RGB( O, , 2 55 ), BF
Line (11 0 , 0 ) - ( 120, 90 ), RGB( 25 5, , , BF

--
1 05
CurrentX = 18 : Currenty = 100

\ Y 1Q

, a Print
Font. Si z e = 14
Pr int ~ W i dg e t Qua r t e r l y Sales"

\ ava

Fo nt . Size = Ol dFo nt Si z e
CurrentX = 2 7 : Currenty = 93

\
Pr int ~ P lanned Vs Actual"
Li n e ( 29. 86) -(3 4. 88) . . . 2 5 5). BF
Li ne ( 43 , 86) -( 4 9, 8 8), RGB(2 5 5, , ), BF
End Sub

--
Widget Quarterfy Sales
PIotnodv,Ao.>uoI

.

6.9. B.r ch.rt

Visual Basic, ( caption


controls, text box control) ! m , bitmap control
! ( m design debug).
, Font.Name (
) , Font.Size ( ) ..
,
( Courier). , ,
( object Screen) ' ( abject Printer).
, ,
:

Pr i vate Sub Fo rm-Cl ick ()


Fo nt .Name ~Modern"

Fo nt.Siz e = 18
Fo nt.Bo ld = True
Print ~ Hell o Vi sua l Ba s i c "
End Sub

--
1 06 - - - -- - - - - - - - --
Font controls , ,
(Name, Size ..), .
picture boxes , FontTransparenl, ,
, ' ,
6.10. ,
.

. 6.10. FontTransparen

FontCount Screen
, Fonts . , Iist box
. '
, object Screen.
Private Sub For.rn-Click ()
Dim

For = Printer.FontCount - 1
Listl.Addltem Printer.Fonts ()

Next
End Sub

Font
, StdFont:
Dim MyFont As New StdFont
With MyFont
Name ''Arial''
Size 10
Bold True
End With

, :

--
[object. ]Print expressionl istJ [{ ; .}}

1 07
":" "." ; ,
,
, ( 14
) . , :

Print ~Basicl " ;: Pr i nt -Basic2"

8as iclBas ic2

Pr i nt "Ba s ic l ", : Pr i nt "Basic2"

Basic l Ba si c 2

(0,0) ,
C en CurrentY,
, :

Private Sub Form-Click )

Cu r r e nt X ScaleWidth / 2
Currenty = ScaleHeight / 2

Print "Hello VB 5.0 "


End Sub

. ,
, TeXHe ight TextWidth.
:

[obj e ct . ] Tex tHeigh t( s t r i nge xpress i on )

(ob j e c t . ] TextWidth (stringexpression)

. , ,
.
t ForeColor BackColor.
Pr ivat e Sub Form-Cl ick ( )

Dim Hal fWidth, Hal fHeight , Msg

Cl s
ForeColo r = RGB(255 , , )

Msg = "Visual Ba s i c "


Fo nt . Si ze = 48
Hal fWi dt h = TextWidth (Msg ) / 2
Hal fHe ight = TextHe ight( Msg ) / 2

--
CurrentX = ScaleWidth / 2 - HalfWidth

1 08 - - - - - - - - - - - -- -- -
Cu r r e nty = Sca leHeight / 2 - HalfHeight
Print Msg
End Sub
. !rc!
!

Visual Basic

. 6.11 . .

1 t
. ,
Tab, :

Tab (column)

,
. 010 6.12.
Priv a t e Sub Fo rm-Cl i c k ()

Cls
Fo nt . Name "MS Sa n s se rif"
Fo nt . S i ze 10
Print
Print Tab( 2 ) ; ' "; Tab (22 ) ; " "
Print String$ ( 62 . .... _" )

f i le$ = Dir$( .... * . *)

While fi le$ <> ""


i = InStr(file$ , - . ")
ext$ = Mid$(file$ , i + 1 )
Select Case UCase$ (ext$ )
Case " "
Desc$ = .... "
Cas e . . ..
Des c $ = " K ~ 1 o "

Cas e "HLP"
Des c$ = " 1 Help"
Ca s e "DLL"
Desc$ = "DLL "
Ca s e " "
Desc$ = " ~ K"

--
1 09
Case El s e
Desc$ ~ U i U + e xt $
End Se l e c t
Pr i nt Tab ( 2); f i le$ ; Tab(22); Des c$
fil e $ ~ Di r $
Loop
Caption ~ U~ v :" + CurDi r$
End Sub

1 1 $ ,, " I. j #.! k& _Io l xl


Qvu

CLJP8DEXE t<:1l
. l I
SMAR.TORV.EXE
REGEDrrEXE
Rie\s .b mp
Squares ,bmp
Zig Zag ,bmp
CALC.EXE
NOTEPADEXE Kioo
PACAGER.EXE
P8RUSH.EXE io
VIRlTE,EXE io
\IN.COM A(oCOM
IOS.INI !
ASPl2HLP.SYS AioSYS
HIMEM.SYS SYS
Crs,bmp
Horeycomb ,bmp
DOSPRMPT.PlF ! PlF
N!NBUG.DAT
WINBUG 1o.0ll L

. 6.12. Tab .

EXTunWTyjt;

,
Printer. Print, PSet, Line Circle
Forit.Name, Font.size ..
; .
Object Printer . PrinlForm :

[fo rm. ]PrintForm

. NewPage :

Printe r .Newpage

, , EndDoc :
Print er. EndDoc

.
:

Privat e Sub Fo r m-Cli ck ()

--
1 10
Dim HWidth, HHeight , , Msg
Er r or GoTo ErrorHandler

Msg = ~Au ~ K o ~

For = 1 2 \

HWidth = Pr inter. Te xtWidth( Msg) / 2 \ ~

HHeight = Printer.TextHeight( Msg) / 2

Print e r. Cu r rentX = Printer.S c aleWidth / 2 - HWidth


Pr inter.Curr enty = Printe r .S caleHeight / 2 - HHei ght
Pr i nter.P rint Msg & Print er. Page & ~.

P rinte r .NewPage \ ~

Ne xt

Print e r .EndDoc \ .

Exit Sub
ErrorHandler:
MsgBox "Yx ~ . "

Exit Sub
End Sub

Page .
, :

Pr ivate Sub Form-Click ()


Dim Header, ,

Print " K~ . .."


Header = "Printing Demo - Page " \ a

Fo r = 1 3
Print er .P r i nt Header;
Printer . Pr i nt Print e r . Pa ge \
= Pr inter.Current y + 10

Printer. Line ( , ) - (Pr inter.ScaleWidth, )

For = 1 50
Printer. Print Str ing ( K. ~ " );
Print er.Pri nt "Vi s u a l Ba s i c ";
Ne xt
Printer.NewPa g e
Next

Printer. EndDo c
End Sub

Printer, default , ,
Copies, , DeviceName,
( . . LaserJet 11151), DriverName (driv-
er) , Duplex,
, PaperSize,
, Port, (.. L1 :) . .

--
, Visual Basic (collection) Printers, -

1 11
.
. ,
defaull.
Dim As Printe r
For Each 1 Pr int ers
If x.Orientation = vbPR QRPortrait Then
\ ~o pr i nt er default.
Set Printe r =

Exit Fo r
End I f
Next

- n

Fading
fading (
, ),
FadeForm . ,
True/False . ,
, Paint :

FadeForm Me , Fa l s e, False , True

Sub FadeForm ( f rm As For.m, Red%, Green %, Blue% )


Dim Sav e Sc a l e %, SaveStyle %, SaveRe draw%
Dim i& , j& , & , & . pixels%

, l l .

Sa v e Sca !e = frm.Sc a leMode


Sa veS t y le = frm.DrawStyle
SaveRedraw = frm .AutoRedraw

, x ; O U .

frm.ScaleMode = 3
pixels = Screen.Height / Sc r e e n. Twi p s Pe r Pi xelY
= pixe l s / 64# + .5
frm.Draw Styl e = 5
frm.AutoRedraw = True
For j = pixels Step

= 24 0 - 245 * j \ p ixels
If < The n =
frm. Line ( - 2, j - 2) - ( Sc r een . Width + 2, j +
+ 3 ) , RGB( - Re d * , - Gr e e n
* , - B l ue * ) , BF

--
1 12 - - -- - - -- - - - - - - -
Next j

, X~K ~.
frm. ScaleMod e "" SaveScale
frm. DrawSt y l e "" SaveSty1e
frm. AutoRedraw "" SaveRedraw
End Sub

l
Rotate.Vbp b~map cantrol OVl '
. v , PSeI.
controls AutaRedraw True ScaleMode 3 - pixel.
Rotate . F :

Defl nt -
Cons t Pi "" 3. 14159265359

~K ~ ~ pitmap pic l

t heta K~ ~ pic2

Sub bmp---Io tat e (pi c 1 As Control, pic2 As Contro l , ByVa l t heta!)


Dim c1 x As I ntege r < pi c1.
Di m c l y As Int ege r < pic 1.

Di m c2 x As I ntege r < pic 2.

Dim c 2y As I nt e ge r pi c 2.
, o~K
Di m " As Si ng 1e /
,
Di m r As Integer o~K

Dim 1 As I nt e ge r pic1. <

Dim ply As I nteger pic 1. <

Dim 2 As Intege r < p ic 2.

Dim 2 As Integer < pic 2.

Di m As I nt e g e r " width or height of pic 2.

~ /

c 1x p i cl.Sca l eWidth 2
cly pic l . Sc a l e Heig ht 2
c 2x p ic2 .Sca l e Wi dt h 2
c 2y p i c 2. Sc aleHe ight 1 2

~K

n "" pic 2.Sc a l e Width


If < pi c 2.ScaleHeight Then pic2. ScaleHeight
"" 2 - 1

~ pixe l pic2.
For 2 "" n
Fo r 2 "" n

1 o ~ K /

If 2 "" Then
a "" Pi / 2

--
1 13
Else
a ~ Atn( p 2y / 2 )

End If
r = Sqr (l& * 2 * 2 + 1& * 2 * 2 )

1 1.

1 = r * Cos (a + theta )
1 = r * Sin ( a + the t a )
V l. 4 pi xels .
cO& p ic1.Point (c1 x + . , c 1y + 1)
c1& pic 1.Point(c1x - , c1y - 1)
c2& pic 1.Point(c1x + 1 . c1y - 1 )
c3& p ic1.Po i nt (c1x - 1, c 1y + plx)
If cO& <> -1 Then pic2. PSet ( c 2x + 2, c2y + 2) . cO&
If c 1& <> - 1 Then pic2. PSet ( c 2x - 2 , c2y - 2) . c 1&
If c2& <> - 1 Then pic2. PSet (c2 x + 2, c2y - 2) , c2&
If c3& <> - 1 The n pic2.PSet (c2x - 2 . c2y + 2) , c3&
Next
, 1 Windows !. 1

t % = DoEve nt s()
Next
End Sub
Yl.a l. 1 30

Pi/6 rads

Private Sub Commandl_Click ()


Static a ngle
an gle = angle + Pi / 6
I f a ng l e = 2 * Pi The n ang le = pi / 6
pictu re 2. Cl s
Call bmp-xotat e (p ict ur e l , picture2 , angle )
End Sub
, bi tmap 1 1 a

Private Sub Command2-Click ()


Er ror Resume Next

file$ = rim$ (nut $ ( " " , ' " ,


"filename.bmp"
If f ile$ = .. .. Then Exit Sub
SavePicture picture2 . lmage , file$
End Sub

--
,,4
_ -

------
~
; . ~i::88-::

" 1

. 6.13. .

conIrols

Draw3d.vbp,
conIrols . MakeBox control, MakeLine
cantrol. Draw3d.Frm,
:

T~ ~ ~ao a

Fo rm-Paint 0 0 on

n: .

AutoRe d r a w n .

Private Sub Form-Paint ( )


Dim cname As Control

For i = (Cont r o l s . Count - 1 )


Set cname = Controls (i )
Ca ll MakeBox (F orm l . c name )
Next
Ca l 1 MakeLine (Fo rml , picture l , 100)
End Sub
pouiva 1 1 i1 0 control

Sub MakeBox (FormX As Form, ct As Cont ro l )


! ct. Left
! ct. Top
2! . Left + . Width

2! ct. + . Height
R& = QBColo r( 15)
$& = QBColor(8 )
FormX.Line ( !, ! - 20 ) - ( 2 ! , ! - 1 0) , 5&, BF
FormX. Line ( ! - 20, ! - 10 ) -( ! - 10, 2! ) , 5&, BF
FormX.Line ( ! , 2! + 10 ) -( 2 ! . 2 !+ 10 ) , R& , BF
Fo rmX. Li ne (2! + 10 . ! ) - ( 2 ! + 10, 2! + 20) , R& , BF

--
11 5
End Sub
1 1 i

c ontrol.

Sub MakeLine (Fo rrnX As Form, ct As Cont rol , i ! )


!

! . + . Hei ght + i !
2! Fo rmX. Width
2! !

R& = QBColo r ( 5 )
S& ~ QBColo r (8 )
Fo .nnX. Line ( ! , ! ) -( 2 !, 2 ! ) , . BF
FormX.Li ne (!, ! + 2 0)-( 2 !, 2! + 20 ) , R&, BF
End Sub

Private Sub Commandl-C l ick ()


End
End Sub

"

"'

. 6.14. .

Kv resize conlrols
Resize.Vbp u u , Re size Fon ,
conlrols , .
:

Sub ResizeForrn( frm As , I n i t As Integer )


Error Res ume Next

Dim ctl As Object


I f I n i t = True Then
For Ea ch c tl f rm.Contro l s
ctl .Ta g = Fo rma t $ ( ct l . Le f t / f rm. ScaleWidth. -. OOOOn) &
Format$ (ctl. / frm. Sc a l e He i ght. " , oooon ) & Format$ (ctl . Wi dt h /
frm. ScaleWidth. .... 0000,, ) & Fo rmat $ (ct l . He i ght /
frm. Sc a l e Height, - . 0000 " )
Next ct l
Else

--
For Each ctl fr.rn.Controls

1 16 - -- - -- - - - - -- - - -
ctl. Move CDbl (Mid$ (ctl. Tag, 1, 5 * frm. ScaleWidth,
CDb l ( Mi d $( c t l . Tag, 6, 5 * frm. ScaleHeight ,
CDbl (Mid$ (ctl . Tag, 11 ,
5) * frm. Scal e Width , CDbl(Mid$(ctl. Tag, 16, 5 *
f rm. ScaleHeight
Ne xt ctl
End If
End Sub

Load , ! TJ e

Private Sub Form-Load ( )


Call Resiz eForm ( Me, True )
End Su b

Resize ! False:
Private Sub Form-Resize ( )
Call Resi z eForm (Me , False)
End Sub

Tag controls.

1.
. button control
PaInt. ; .
;

2. ( Picture box control


). , ,
, , .
.

3. ; . ,
.

4. .
()
.

5. .
.
. ,
.
. , "" , .

--
11 7
6. progressbar control
( .
) . :

Sub DrawProgress ( As Integer, As Int e g e r , w As Int e g e r , h As Integer,


run As int eger)

, , w, h nm
1 100 ( ,
) . %.

7. '
.
, , , l
.

-
-.
1 18

Visual Basic (mouse),


conIrols,

button S H IF,
, CTRL
buttons . , drap-and-
drop, control .
, Visual Basic 5.0 L Drag & Drop,
.

[ (rnOU5e eveJ)t5)
control s
.

MouseDown .

MouseUp .

MouseMove .

controls 10 , '
. ,
control
,
:

bits (least-significant bits) U .

Shitt bils (Ieasl-signijicanl bijs) SHIFT, CTRL


.

, , ( I)
.

--
1 19
, Imagecontrol (
), button { :

Private Su b Fo rm-MouseDown (Butt on As I nt e g er. Sh i f t As I nt e g e r. _

As Sing le . As Si ng l e )
I ma g e l .Mo v e - Imagel .Width / 2. - Imagel.He ight / 2
End Sub

. DrawWidlh
ForeColor , MouseMove
, button ,
MouseUp.
Dim PaintNaw As Integer
Private Sub Form......Load ()
DrawWi dt h 10 ~
Fo reCo l or = RGB(O. , 255 ) '

End Sub

Pr ivat e Su b Fo rm-MouseDown (Button As Integ er, Sh ift As Integer, _

As 5ing1e , As 5ing1e )
Pa i nt No w = True '

End Sub

Pri vat e Sub Fo rm-MouseUp ( Butt o n As Inte g e r, Sh i ft As Int ege r , _

As 5 ing 1 e , As 8 ing1 e )
PaintNaw = Fals e \~ n

End Sub

Priva te Sub Form-MouseMov e ( But t o n As Int ege r , Shift As Integ er. _

As 5 ing1e . As Single )
If PaintNow Then
PSet ( , ) , ~6

End If
End Sub

11 ~""

. 7.1. .

ButtoJ)

--
. ,

1 20
MauseDawn, , ,
MouseUp, button .
:

vbLeftButton( ~ 1) button o K o t .
vbRightButton(= 2) button .
vbMiddleButton(~ 4 ) button .

, :
Pr ivate Sub Forffi-MouseDown(Bu t t o n As Integ e r , Sh i f t As Intege r, As
Single , As Single )
If But t o n 1 Then MsgBox ~~ ~6 butt on"
! Button 2 Then MsgBox ~ l butt on "
If Button 4 Then MsgBox Ula button"
End Sub

Button, MouseMove,
buttan , , -
:

button .

3 n , .

7 buttons.

buttan, :

Pr i v a t e Sub Fo rm-Mo useMove (But t o n As I nt e g e r , Sh ift As I nt e g e r ,


As Si ng l e , As Single )

! Button = 1 Then MsgB ox ~~o 10 b utton"

End Sub

, buttan.
And :

Pr ivat e . Sub Fo rm-Mou seMo ve ( But ton As I nt eger, Shift As I ntege r , As


S ingle , As Sing l e )
I f But ton And 1 Then MsgB ox 1 10 but t o n "
I f Butt on And 2 The n MsgB ox " 1 b ut t o n "
If ( But t on And 3 ) = 3 Then
Ms g Bo x "1 KO~ 1 0 1 butt on"
End I f
! ( Button And 7 ) = 7 Th en
Ms g Box " ~ oo but t o n s OV 1K 1 0 "

End I f

--
End Sub

1 21
" StJft

Shift Button.
SHIFT, CTRL buttons .
:

1 SHIFT.
2 CTRL.
3 SHIFT CTRL.
4 .

5 SHIFT .

6 n CTRL .
7 SHIFT, CTRL .

And , :

Private Su b Forffi-Mous eDown ( But t o n As Intege r, Shift As Integer, As


Sing l e, As Single )
If Button And 1 Then MsgBox ~ 8H1F T "
! Button And 2 Then MsgBo x ~ CTRL "
If Button And 4 Then MsgBo x U ALT "
If ( But t o n And 3 ) = 3 Then
Msg Box " 8H1FT KQl CTRL . "
End If
If ( Butt on And 5) = 5 Th e n
MsgBo x " ALT KQl 5H1FT ."

End !

If ( Butto n And 6) = 6 Then


Ms gBox " ALT KQl CTRL . "
End !
If (Button And 6) = 6 Then
MsgBo x " ALT, 8H1F T KQl CTRL ."

Ed !

End Sub

Drf{J - ffI d - Drop


Visual Basic, controls
. / drag-and-drop
. ,
control, dragging, dropping.
; controls ,
. control (dragging),
, OVKO . m run-time

--
control , ' , .

122
,
controls ( menus tlmers) drag-and-drop:

DragMode control.
Draglcon control.
DragDrop control (dropping) contro!.
DragOver control (dragging)
control.
Drag u (dragging).

(dragging) control DragMode


1, :
Contro l.OragMode 1

. dragging, control
.
, dragging
Draglcon, design runtime .
:

Imagel . Draglcon = I ma g e 2. Dr a gl con

' Image controls,


LoadPicture, - ( bitmap):
Image l .D rag lcon = LoadP ict u re(Uc: \ vb\ icons \ drag lpg. ico")

drag-and-drop source target,


:

Souc e control (dragging). menu ti m e .

Target ( control) (dropping) control


DragDrop.

DragDrop , source, control ,


, , control con-
trol. :

P riv a t e Sub Fo rmLDr a gDrop (S o urce As Cont ro l , As Si n g le. As Si ngle )

End Sub

, Source control,
11 ... Then ... Else TypeOf.
DragOver, ( control) ,
' control, ( ) :

--
Private Su b Fo rmLDr a g Ov er (S o urce As Contro l, As Si n g le , As Single ,

1 23 - - - - - - - - -- - - - - - -
State As Integer)

End Sub

State control.
control, ,
:

c ont ro l .D ragMode

Drag, :
contro l . Dr ag 1

DragDrop, 2,
:

contro l .D r ag 2

Drag.
, command button .
MouseDown, MouseUp DragDrop.
DragX DragY, control,
MouseDown. Drag,
MouseUp:

DefInt -

Di m DragX As Sing l e . DragY As Singl e

Private Sub Commandl-Mou s e Down (But t on As In t e ge r . Shi f t As In teger, As


Si ngle, As Single)
Cornmand l. Drag 1
DragX

DragY =

End Sub

Private Sub ComrnandL-MouseUp (Button As Int ege r . Sh i f t As Integer, _


As Si ngle , As Single )
Command l.Drag 2
End Sub

Pr ia te Sub Form-DragDr op ( Source As Cont r o l , As Single . As Single )


Source.Move ( - DragX) , ( - DragY)
End Sub

command button l
. .
Drag.Vbp '
drag-and-drop. drive , dragging
Image control. , ,
, , .txt

--
NOTEPAD.EXE . .

1 24
.. Dra.g ond Drop I!lIiIEJ
18 ., J cal IIog.tt

t]: D:\
..
L] -wps _Ip
cardfile.ex e
cardfile.hl

carved sto n e . bm~


castle walls.bmp
[J a pw_data
ccard20 0.exe
[] comman d cdplayer.exe
D config clipbd.exe
D cookies ~

. 7.2. Drag.Vbp.
drive list box, directory list box l list box controls,
. .
Drag .Frm:

Private Sub Fo r ffi-Loa d ( )


frmD rag.Width = 652 5
f rmDrag.Height = 3 075
End Sub

control filel niPVEl a Dri v e l KQl


v n dragging Drag

Prlvate Sub File l -MouseDawn( Button As I nteger, Shift As Integer, As


Single. As Single)
f i le l . Draglcon = Drive l . Draglcon
fi l el . Dr a g 1
End Sub

contro l (fi l el ) I ma g e c o n t r ol.


o uvtXE1Q xov ~ o ,


Shell Yla ~o . Yla
(bitmap . . .), \Jll Image.

txt ., , ,

hlp , Win Help.EXE.

Private Sub Ima g el-Dra gDr o p ( Sou r c e As Control, As Single, As Single

, FileName
temp ~ Ri ght $ ( f i l e l . filename , 3)
If Mid(file l.Path, Len(fi lel. Path = ~ \" Then
dropf ile filel .Path & f i l e l . f i l e n ame
Else
dropfile f i l e l . Pa t h & ~ \" & f ile l. f ile n ame
End I f

--
' control

1 25 - - - - - - -- - - - - - - -
im agel.Picture = LoadPicture ( "")

dragging 1

' . .

Sele ct Case Lc a s e $ ( t e mp )
Case "txt"
= She ll ("Notepad " + dropfile . 1)
Case "bmp" , "wmf" . "rle ", "ic o "
i ma g e l . Pi c t u r e = LoadPicture(dropfile )
Case "e xe"
= Sh e l l ( drop fi l e, 1)
Case "hlp"
= Shell ( " Wi n He l p " + dropfi l e , 1)
Case Else
msg "T ry one of t hese file t y p e s : "
msg vbCrLf + msg + vbCrLf + v b Cr Lf + " . tx t , .bmp, .exe, . hlp "
MsgBo x msg
End Select
End Sub

State DragOver 1 3 1 .

1 1 1 1

t a rget 1 1 , 1

1 10 1 1 2

1 a 1 0 .

, 1 0 Image control,
1 target , 1 10,

control n

1 v contro ls Dirl 1 Drivel 1

design .

Private Sub Imagel-D ragOver(Source As Contro l. As Single, As Single ,


State As Integer )
Select Case State
Case
filel .Draglcon Dirl.Draglcon
Case 1
filel .Draglcon Dr ive l .Draglcon
End Se l e c t
End Sub
Private Sub Dirl_Change ( )
f i lel.Path = Dirl.Path
End Sub

Private Sub Dri vel-Ch a n g e ( )


Dirl.Path = Drivel.Drive

--
End Sub

1 26
J "

VisuaI Basic
, , cantraI , ,
. MousePointer :

o bject .Mou s e Po i n te r [= v alue]

, .
,
:

(Defautl). .

1 (Anow).
2 (cross-hair poin!er).
3 I-Beam .

4 .

11 (Hourglass).
12 ,

13 .

14 .

99 Mouselcon.
Screen, .
11 ( ) , 1
, :

Pr ivate Sub Form-Cl i c k ()


Dim

Screen.Mou sePo inter = 11 \ 1 O V1K1 0

Fo r = Sc aleWidth St e p 50
\ 1 1 1

ForeColor = RGB( Rnd * 255, Rnd * 255 , Rnd * 255 )


Ci rcle (, Sc a l e Heigh t * Rnd) , 400
Next
Screen.Mo usePo i nte r = \ 1 1

End Sub

13 ,
, ; .
, DoEvents,
, custom control.
, Mouselcon ,
MousePointer 99. :

object. Mou s e l con = LoadPicture( pa thname)

--

- - -- - - - - - - - -- - - 127 - - -- - - - -- - - -- - -
object.Mouselcon = p ict ure

auT u .CUR,
. (animated cursor).

DrAg d Drop
Visual Basic u u Drag & ,
, ' u controls
. Visual Baslc 5.0, u u
L Drag & Dro , u . u
u OLE, u C/C+ +.
Word ,
, Excel u u .
Source application
u Target .

, l;} UJjd
L Drag and u 9 ,
u u u.

OLEDragMode control Source


.

OLEDropMode control
(largel).
OLEOrag L Drag and
.

OLECompleleDrag
Drag andDrop.
OLEDragDrop control
OLEDrapMode .

OLEDragOver con-
trol OLEDropMode .

OLEGiveFeedback control source


TOU.

OLESelDala source control, target control


OLEDragStart.
O L ESlatOrag L Drag and ,
.

- - - -- - - - - - - - - - -
--
128 - - - - - - -- - - - - - - -
L
,
Drag Source L
,
Drop Target

- eenls: TargeI-side evenls


OLESIarIDrag OLEDragDrop
OLESeIDaIa OLEDragOver
OLEGieFeedback
OLECompleteDrag

. 7.3. Drag and Drop.

J)ffj!J fjJld J)fOP


,
Visual Basic, . ,
, .
L Orag and controls. OBGrid, Image, Picture
box, tet box (dragging) (dropping).
controls ComboBox, DBCombo, Dblist, DirListBox, FileListBox Listbox
.
controls, checkbox, CommandButton, Frames, label, optionbutton,
form s, L Drag and Drop.

' textbox COJltfoI


tetbox control
Automatic m OLEOragMode OLEDropMode. ' ,
tetbox , . .
NotePad. NotePad, Ctrl,
.
L Drag and Drop, Source,
, : OleStar1Drag , OleSetData,
OleGiveFeedBack OleCompleteDrag . Target, ,
OLEDragDrop OLEDragOver.
m
OLEDrag OLEDrop .

VbO leDragAutomatic riVEToL i L Drag and , xj


control .

VbOleDragManual .

VbOleDropautomatic control / .

VbOleDropManual control ,i .

VbOleDropNone - .

- - - - - - - - - -- - -- -
--
129 - - - - - - - - - -- - - - -
target
' .

OLEl>rfjgOver

OLEDropMode, OLEOragOver
target, . :
Private Sub Forrn-OLEDragOver(Data As Da t aObj e c t , Ef f e ct As Long, Button As
Int e g e r , Sh ift As rnteger, As Single, As Single , State As I nteger)

,
GetFormal. , DataDbject
Effect :

VbDropEftectNone i Drag and yiVEl.


VbDropEftectCopy .

VbDropEfteclMove yiVEl .

VbDropEfteclScroil
.

, Shift,
. State :

VbEnter Source control target.


VbLeave SOU ce control target.
VbOver Source control target , target.

OLEl>rfjgl>rop
target,
OLEDragDrop. GetData,
. :

Private Sub Form-OLEDragDrop(Data As DataOb ject , Effec t As Lon g , But ton As


I nt e ge r " Sh ift As I nt e g e r , As S ingle , As Si ngle )

Textl .text = Da t a . Ge t Da t a (vb CFTe xt )


End Sub

Effect OLEDropEffects.

, Shift, ,
OLEDragOver.
dragdrop.vbp textbox control , image control
o pto buttons controls ( 7.4.). Image Stretch
True, Multiline textbox control.

--
1 30
lIIri foIm1 I!!I[!]E'J
rNone

DRAG DD
MicrO$Ol!: Visu31 Ba,oc
noI >..rlOOtptI
Drag t.
,.
DragMode . Draglcon
'({'- DragDrop
DragOer , : (lIJTt.. ..
&~~c .. _

. 7.4. dragdrop.

u i ;

Option Explicit
Private m-effect As Long
Private Sub Form-OLEDragDrop(Data As DataObject, Effect As Long,
Button As Integer, Shift As Integer, As Single, As Single)
I f Da t a. Ge t Fo r ma t ( v b CFTe x t ) Then
Print "Text "
Textl.Text = Data.GetData(vbCFText)
ElseI f Data.GetFormat(vbCFBitmap) Th e n
Pr int "Bitmap"
Set Imagel.Picture = Data.GetData(vbCFBitmap )
ElseIf Data.GetFormat(vbCFMetafi le ) Th en
P rint "Metafi le"
Set Imagel.Pictu re = Data .GetData ( vbCFMetafi le)
Else If Data.GetFormat (vbCFRTF ) Then
Print "R ich Te x t Format"
End If
End Sub

Private Sub Form-OLEDragOver(Data As DataObject, Effec t As Lo n g ,


Button As Integer, Shift As I nte g e r , As Single, As Single,
State As Integer)
Effect = m-e ff e c t
End Su b

Private Sub Op t i o n l _ Click ( )


m-effect = vbDropE ffectCopy
End Sub

Pr ivate Sub Option2_C lick()


m-effect = vbDropEffectMove
End Sub

Private Sub Opt ion3~Click()

m-effect = vbDropEffectNone

--
End Sub

1 31
, ,
WordPad . , Textbox Image con-
trol. Microsoft Windows Paint L Drag and Drop.

:
L
Orag and Drop, OLEDrag,
MouseDown source control. :
Priv ate Sub Fo r.m-MouseDo wn (B utton As Inte g e r , Sh ift As I n t e g e r,
As Sing le , As Singl e)

Forml .0LEDrag
End Sub

OLEStartDrug
OLEDrag source
control , OLEStartDrag, :

Pri v a t e Su b Fo r rn-OLESt artD r a g( Data As Da t aOb ject . Allo we dE f f e cts As Long )

End Sub

,
Data, DataObject.
, AllowedEffecls
L Dragand .
OLEDropEffects. :
Pr iva te Sub Fo r rn-OLEStartDra g (Data As Da t a Obj e c t , Al lowedE ffects As Long )
All owe dEffect s = vbDr o pEf f ectCopy And v bDropEffectMove
End Sub

DataObject
Clear, files, GetDala, Gelformat SetData,

.

Clear DataObject /

Files u VBFilesFormat.
GetData nou u Clipboard U /
OataObject.
GetFormat DataObject.
SetData DataObject.

OLEStartDrag, o~oo
SetDala, . :

Pr ivat e Sub Form-OLESta r tD rag (Data As DataObject , AllowedEffects As Lo ng)


Al l owedEffect s = vbDropE f f ectCopy And vbDr OpEf f e ctMo v e
Da ta.$e t Data "Hey The r e" , vbCFText

--
End Sub

1 32
vbCFBitmap,
vbCFDib, vbCFiles, vbCFMetafiles, vbCFEMetafiles, vbCFPalette, vbCFRtf, vbCFLink vbCFText,
.

VbCf Bi!map bitmap ( . ).

VbCf Oib bitmap ( . I ).

VbCf f iles (Windows Explorer).


VbCf Metafile Me!a!ile (.WMf)VbCf EM e!afileEnhanced mefafile (.EMf).
VbCf Palette

VbCfRtl (.RTf).
VbCfText ( .) .

L Drag and Drop


Clipboard Windows, .
source L Drag and Drop.
textbox control. ,
control.
dragdrop.vbp:
Opti on Expli c i t
Privat e Sub Fo r ffi-Mou s eDown (Button As Int ege r , Sh i f t As Int e g e r , As
Sing le , As S i ngl e)
Forml. OLEDr ag
End Sub

Pri vat e Sub Forrn-OLESt a rtDr a g (Da t a As Da t aObj ect , AllowedE f f ects As Long)
Al lowedE ffect s = vbDropEffectCopy
Da t a . SetData Te xtl .Te xt, v b CFTe xt
End Sub

OLESetDctc
target,
, .. .

, (Delayed rendering),
(rendering) ,
:

Pr i v a te Sub Form-OLE St a rtD rag (Data As Dat a Obj e ct , Al l owe dEffe cts As Lo ng )
Al lowedEffe ct s = vbDr o pEffectC opy And v bDropE ff ectMove
Data. Set Da ta. vhCFText And VbcfBitmap And v b c fMet afi l e And vbc f RTF
End Sub

, ,
. larget -
OLESetData, SetData,

--
.

1 33
Pr ivate Sub Form-OLESetDat a (Data As DataObj ect , DataFormat As Int ege r )
Select Case Dat aFo rmat
Case vbCFText
SetData (Re qu e s t e d da t a here ] , Da t a Fo rmat
Case vbCFRTF
SetData (Requested data h ere] , DataFormat
Case v b CFMeta f i l e
SetData (Requested data here ] , DataFormat
Case v bCFBitmap
Set Data (Requested data here] , DataForm at
End Select
End Sub

OLEGLvefeedfiuck
Drag and
L
target,
. , Effecl Defau ~Cursors.
Effecl vbDropEffecl
Defau~Cu rsors Windows
. False
Mousepointer.

Private Sub Form-OLEGiveFeedback (Effect As Long, De faultCursors As Boolean)

Effect = vbDropEffectCopy
End Sub

OLEC.ornpletel)rug
OLECompleteDrag .
Effect, source
, ..
(vbDropEffecIMove) .

Private Sub Forrn-OLECompl eteD r ag (Effe ct As Long )


If Ef fec t = vbDropEffectMove Then
, ~ K~K

End !
End Sub

I) urd I)rop ,IILrdow5



Explorer Windows, GetFormal
vbCFFiles:
Priv a t e Sub Fo rm-OLEDragDrop(Data As DataObject, Effect As Long , Butt on As
Int ege r , Shift As I nteger, As Singl e , As Si ngle)
! Data. GetFormat( vbCFFiles) Then

, a Explore r Windows
End !

End Sub

--
1 34
, Data.Files
DataObject.

Count .

110m .

CIoar .

Remove .

, OLEDropMode
1 - Manual. , , Windows Explorer,
, .

Opt ion Explicit

Pr ivat e Sub Form-OLEDrag Drop(Data As DataObject , Ef f ect As Long, But ton As


In teger, Shi f t As I nt e ge r, As Sing l e , As Singl e )
Dim Count As Integ e r

I f Data.GetFo rmat {vbC FF i les ) The n


Print ~Ax Windows Explorer #
For Co unt = 1 Data. Files . Count
Pr int Da ta. Fi le s(Count)
Next Count
En d r f
End Sub


text boxes controls

Windows 95, '
box contral, menu (Cut, Capy ..) .
MauseDown teX box,
default , Menu1 :

If Butt o n = VbRightBut t on Then


Te xt l. Enab l e d = Fal s e
Textl.Ena hled = Tr ue
Textl . Set Fo c u s
Po pUpMenu Menul
End If

cantrol Windows
MouseDown. PapUpMenu,
.

--
1 35
"Tag Tips"


Tag.Vbp
tag tips controls . ' ' label control
AutoSize True. tag controls
MouseMove :

Priva t e Sub CommandL-Mous eMove (Button As Int eg er, Shlft As Integer, As


Single. As Single )
Call P utT ag (Commad l )
End Sub

PutTag :

Sub putTag (ct r As Cont rol )


Label l .Ca ption = ~ ~ + ctr. Tag + ~

Lahe l l. Top = ctr. Top + ct r. Height


La b e l l .Le f t = ct r .Left + ctr.W idth / 2
Labell.Visi b l e = True
End S ub

MouseMove :
Private Sub Fo rm-MouseMov e(Button As Integer, Shi f t As Intege r , As
Sing l e , As Single )
Labell.Visible = Fa l s e
End Sub


Circle.Vbp
(,) , :

* + * <= r * r

, ,
(0,0), :

Scal e (-Scal eWidt h / 2, ScaleHeight / 2 )- ( Sc a leWi dt h / 2, -Scal e He i ght / 2 )

. :

Dim mRadi u s As Single


,

Privat e Sub FormLPa int( )


, t wips
Scale
Cl s
FillColor = vbRed
FillSty l e = vbSolid
I f Sc aleHeight < Scale Widt h Then
rnRadi u s = (Scale He ight / 2 ) - 30
Else

--
1 36
mRadius (ScaleWidth / 2) ~ 30
End I f
,

Scale (- Scal eWidth / 2, ScaleHei ght / 2) -(ScaleWi dth / 2, - ScaleHeight / 2 )


DrawWi dth = 1
Ci r c le (, ) , mRadiu s
En d Sub
\ ~o l l

Private Sub For....Mou s eUp (Bu t t on As I nt e ge r , Sh ift As Int e ger, As


Single, As Si ngl e )
Scale (-ScaleWidth / 2, ScaleHeight / 2 )- (ScaleWi dth / 2, - Sca l eHe i ght / 2)
I f But t on = vbLe f tButt on And ( * + * < mRa d i u s * mRa d i u s ) The n
MsgBox " c l ick "
End I f
End Sub

(dragging) item list box


item list
box control ( ) drag-and-drop.
TexlHeight TopIndex list box.
TextHeight listbox.
, , L sDragDrop,
Ilst box
item. , Toplndex (Index) item listbox.
, item.
Droplist controls, filelistbox listbox control.
dragging , ""
.

Forml I!lOOf3
_vp sup .eKe
- - ufile.tmp ac csIal.eJle
- u phreg.da t alarm.ini
32k.cmeO.d ll
ac ce ssor_gp

accsaee

acroIead.in
aC fosch.ini
ag ility. ni
alarm .ini
ald lea rn.d ll ~~
ap iload _ini ..:.J

. 7.5. Droplist.

Droplist. Frm:
Deflnt -

Private Sub F i le ~o use D o wn (Button As I nteg e r , Shi ft As I nt eger, As _


Single, As Single )

--
1 37
Fil el .Dra g 1
End Sub

Sub Lis tl-DragD rop ( So u r ce As Control , As Single . As


Si ngl e )
& = Listl.Toplndex

ColumnH eight = TextHeight (~A ~)

Inse rtI& = \ ColumnHeight


file$ = Filel.FileName
If I ns e r t I & <= Li stl. ListCount Then
Listl. Addl t em file$, Inse rtI& + &
Els e
List l . Addltem file$
End If
End Sub

con\rols
Dragdrp controls
. command button controls
, (Vislble = ) . [ ,
.
. Paren\ con-
trols ( - ) .

.. Forml 1!!I~f3

! Butlon 1
Buto"
lon 2

Bulon 3

B ulOll ..

. 7.6. controls 2 .

Dragform.Frm:
De f l nt -

l KQl
Load, l 4 l controls

Commandl, KOl l ll .

Private Sub FormLLoad ()

, l

Move . , Sc reen.Width \ 2

--
1 38
F orm2 . Sh o w
Comrnand 1 (0 ). Top =

Command1( 0 ).Left = 1 0 0

Fo r i % = 1 4
Load Comrna nd1 (i %)
Comrna n dl (i %).Le f t = Comrna n d1( i % - 1 ) . Left
Comman d l ( i %).To p = Cornmand1(i % - 1 ) . +
Cornman d1( i % - l).He i g h t
Comrnand1 (i %) .Capti on ~Button " + Str$ ( i %)
Command1 ( i %) . Vi sible = - 1

drap-and -drop 1

Comma n d 1 ( i %).DragMod e = 1
Ne x t i %
Comma n d 1 (O ) . Ca p t ion = ~Butt on Ow
Comrna nd1 ( O) . Vi s i b l e = -1
Comma nd1 (O ) . Dr agMode = 1
End Sub

1 Sou rce cont ro l 1 (dro p ping)


. 1 1 1 P arent .
1 10 1

c ont r o l .

1 1. 1 .

Private Sub Fo rm-D ragDrop ( So u r c e As Cont r o l . As Si ngl e . As Sin gle )


P arent % = Source.Parent .hWnd
If Pa r ent % <> Fo rml . hWnd Th en
Ind ex % = So u r c e . I n d e x
Comman d 1 ( Index %). Ca p tio n = So u r c e. Ca p t ion
Comman d l ( I n d e x %) . Le f t = - So u rce .Width / 2
Comrnand l ( Index %). To p = - Sou r c e.Heig h t / 2
Comrna ndl ( Index %). Wi d t h = Sou r c e.Width
Comrna n d l ( I n dex %).Height = Sourc e .Height
Comma n d 1 ( Inde x %).Vi sib1e = - 1
So urc e. Visible =
El s e
So u rce . Mo v e - So u rce. Width / 2, - Sou r c e . Heig ht / 2
En d I f
End Sub

1 Dr opfo rm.F rm :

1 1 1 10

1 1 comman d b utto n s 11

Vis i ble =

P r i v a t e Sub F orm-Lo a d ()
Move Sc r e e n . Wi dth \ 2 . , Sc r e e n . Wi dth \ 2

~
139
~
Command1( O) . Visible

For i % = 1 4
Load Cornmand 1 ( i% )
Commandl (i %) .Top = Command1{i% - l ). +
Commandl (i % - l) .Heig ht
Command l( i% ) .Visible =

Next i %

End Sub

, ~

Pr ivate Sub Form-DragDrop ( Sourc e As Cont r o l , As Single , As S inql e)


Pa r e nt % = So urce . Pa rent.hWnd
If Parent % <> Form2 . hWnd The n
Index% = Source. Index
Commandl ( I nde x %) .Capt ion = Sou rce.Caption
Comman dl ( I n dex %). Left = - So urce. Width / 2
Commandl(Index %). Top = - Source. He ight / 2
Commandl(Index %) .Width = So u r c e.Width
Commandl (Index %) .Height = So urce.Height
Command1(Index%) .Visible = - 1
So u r c e .Vi s i ble =
Command l ( I nde x %) . Dr a g Mo de = 1
Else
Sourc e .Move - Source .Width / 2, - Sou r c e . He i g ht / 2
End I f
End Sub

1. Visua/Basic;

2. MouseMove.

3.

Drag & Dro;
Drag & D.

4. Drag & D Drag & D;

5. Drag & D.

6. ;
;

1. command bulton controi. ,


' , control
.

--
1 40 - - - - -- - -- - - - - --
2. ,
text bo control. '
, .
. control .

3. p ictu rebo controls .


, .

4. text bo control hyperte t . focu s


URL ( @ http://),
"" Undertine .
, control . control focus,
.

5. ' . ,
, .

--
1 41


( ..) ,
(keyboard). , controls
:

KeyDown .

KeyPress . ASCII.
KeyUp .

! SIIJ GII] g 1~I~:I;

-
. ,: : : ~ ; : : : ' : -
18~ 1 ' " ' ' " ' . : Ii It 9 ... w ;:'
~
, t, ,
_

"" ' ' ' ' " ' ' ' : : "',
.-t..rfb . . ... - +
,~

' ''''f! , , ' ~ ~


,, , ,

:J - " t + ...

. 8.1. " " .

control (focus), ,
, controls (disabled).
controls KeyPreview True,
.
KeyPress ( ) :

Private Sub F orm-eyPress (KeyAs c i i As Intege r )

--
1~3 - - - - - - - - - - - - - - -
KeyAscii ASCII
, CTRL
, Enter Backspace.
KeyAscii , :

Chr $ (Ke yAs c i i )

KeyAscii default
controls, ,
text box:
Pr ivate Sub Text L-e yP re s s (Ke yAscii As Intege r )
Ch a r $ = Chr$ (KeyAs c i i)
KeyAs cii = As c( UCas e$( Char$))
End Sub

, Enter command button


control Default, .
Enter KeyPress.
Pr i v ate Sub Te xtl-eyPre s s (KeyAscii As In t eger)
I f Ke yAs c i i = 13 The n Ke yAs c i i =
End Sub

KeyDown KeyUp
( ) ( control) (focus).
:

Pr ivat e Sub F o rm-e y D own ( Ke y Code As Int e g er, Sh ift As Int ege r )

Private Sub F orffi-e y Up (KeyCode As Intege r , Shift As Integer )

KeyCode ' , vbKeyF1 ( Fl),


vbKeyHome (
Home) ..
Shift SHIFT, CTRL ,
. (Ieast-significant) bits, 1
SHIFT, 2 CTRL, 4
. , ,
. , CTRL ,
6.
, controls, True
KeyPrevIew, KeyDown
controls:
Pr ivate Sub Form-L oad ()
KeyPr eview = True
End Sub

Privat e Sub F o rm-e y D o wn ( Ke y Co de As I nteger , Sh ift As Integer )


Se lect Ca se Key Code

--
, .... - - - - -- - - - -- -- - - -
,
Case vbKeyFl: MsgBox . "
,
Case vbKeyF2: MsgBox F2 . "
Case vbKeyF3: MsgBox F3. "
,
Case vbKeyF4: MsgBox . F4. "
End Select
End Sub

, F2,
SHIFT, CT R text bo cantral.
Private Sub et-eDwn (KeyCode As Integer, Shift As Integer)
Dim ShiftDown, AltDown, CtrlDown, Txt

, Shift
ShiftDown = (Shift And vbShiftMask) >

AltDown = (Shift And vbAltMask) >


CtrlDown = (Shift And vbCtrlMask) >

! KeyCode = vbKeyF2 Then


! ShiftDown And CtrlDown And AltDown Then


Txt = ~Shift + Ctrl + Alt F2.
Elself ShiftDown And AltDown Then
Txt = ~Shift + Alt F2.
Elself Sh iftDown And CtrlDown Then
Txt = ~Shift + Ctrl + F2.
Elself CtrlDown And AltDown Then
Txt = ~Ctl + Alt + F2.
Else lf ShiftDown Then
Txt = "Sh ift F2. "
Else If CtrlDown Then
Txt = "Ctrl F2.
Elself AltDown Then
Txt = ''Alt F2 ."
ElseIf Sh i f t = Then
Txt = "F2."
End If
Te x t l . Te xt = "l " & Txt & " "

End !

End Sub

--
1 45
- (


tet boxes controls ( )
, CAPS LOCK, KeyPreview
True KeyPress :

Pr i v ate Sub F orm-eyPre s s(KeyAsci iAs Integer)


Ke yAscii = As c (UCase(Chr$(KeyAscii)
End Sub

teX box cantral


tet box,
tet box control:
Pri v a t e Sub TextL-e yUp(KeyC ode As I n t e g er, Sh ift As I nt e g e r )
!Len(Me . Active Control.Text) = Me . Activ eCont rol.MaxLength Then
Sen deys ~{ TAB }" , Tr ue

End I f
End Sub

l teX boxes
tetboxes controls
Enter. , controls Insert.

, tet boxes Enter
Insert. , InsertMode. tet boxes
controls, Index .
KeyDown KeyPress:

DefInt -

Dim I n s e r t Mo de As Intege r

Pr ivate Sub e t-eDwn ( I nde x As Intege r , KeyCode As Integer,


Sh i ft As Integer)
I f Key Code = vbKeyInsert Then
In s ertMode = Not I nse rtMode
End If
End Sub

Pr i v a te Sub et 1-eress {Index As Inte g er, KeyAsc i i As I nt e g e r}


I f KeyAsc i i = 13 The n
KeyAsc i i =
S e nde ys "{ Tab } n
End I f
If InsertMode Then Tex t1(Index }. Sel Length = 1
End Sub
SendKeys (keystrokes)
( ) controi, -

- - -_ - - - - -- - - - -
--
146 - - - - - - - - - - - -- -
,-------------------...dft
r~
, . ~ =iI't
, SelLength ' text box ( combo box) ~l::~
(selected), SelText - .....
.

buttan bitmap cantrol



command buttons Visual Basic
, 3 command buttons
bitmap . ,
bitmap control ' command button button
,
.
bitmap .

AutoRedraw True
AutoSize True
BorderStyle -

DrawMode 6-lnvert

,
DrawMode 6,
. Picbutn.Frm, ,
4 bitmap KeyDown, , MouseDown MouseUp,
DblClick. L .

Private Sub Picturel_Click ()


Beep
End Sub

Private Sub P ict urel-Db lCl i c k ()


Pictu re l .Line ( , O)- ( P i c tur e l.Wi d t h , Picture l .Height) , , BF
En d Sub

~ ~ ENTER SPACE Vl Q
V l El K6v a

Private Sub Picturel~e yDown (Ke yCo de As I nt e g er, Shift As Inte ge r )


I f Ke yC o de = 13 Or KeyCo d e = vbKe yS pace Then
Pict u r el. Line ( . O) -( P i c t u r el. Width . P i c tu r e l . Height), , BF
End If
End Sub

l ENTER SPACE 1

Click 1

button.

Private Sub icture-eU (KeyCode As I n t e g e r , Shift As Intege r)

--
I f KeyCode = 1 3 Or KeyCode = vbKeySpa ce Then

1 47
P i c t u r e l . Line ( , O) - ( Pictu r e l . Width , Pi c ture l . He ight) , , BF
PictureLCl i c k
End !

End Sub

Pr i v a t e Sub Picturel-Mous eDown ( Butt o n As Int ege r . Shift As Int eger, As


S i ng le , As S i ng le)
Pictur e l . Line ( , O) - ( Pictu re l. Width. Pic turel .He i g ht) , , BF
End Sub

Priva t e Sub Pict u re l-Mou s e Up ( But t o n As Int e g e r, Sh i f t As Intege r .


As Single, As Si ng le)
Pict ure l . Li ne ( , O) - (Pi ct ure l . Width, Pictu rel. Hei ght ), BF
End Sub

1. Copy Paste textbo control.


Ct~ + C Ct~ + V ASCII 3 22
.
2. 5 l nde text bo controls
labeI controls, :

, ', , , , ,

:
. & .
. Edit
, : ; -
. Tab, Enter. ,
lnsert.

3. captIon
(ASCII). Shift CI1 .

4. .
. , "
. Backspace.
m
;

5. ,
.
. , .
. Backspace, .

--
, 048
-

coJItrofs...
controls, text box command


button control, events . Visual Basic
, , '
controls. cantrols (custom controls ) OCX.
Visual Basic, text box command
button control, controls.
controls .

coTItrols
controls Visual Basic.

fn.lTJJe
Framecontrol controls,
.
frame controls
. , frame
.
, controls
Framecontrol. CTRL con-
trols .

Caption. Run time - ,
' , :

Framel .Capt ion = UNew title"

--
events , Click DblClick.

1 49 - - - - - - - - - -- - - - -
iIII Forml I!I[ilEJ
F'l!le1

:. ao

. 9.1. frame controls.

, caption Framecontrol,
Static:
Pr ivate Sub Commandl-C1i c k ()
Static 8 0 0 1 As Integer

If 8 001 = The n 800 1 = 1 E1se 0 1

If 8 0 0 1 Then
Frame l . Capti on = "True"
Els e
Fr ame .Cap t ion = "Fa lse"
End I f
End Sub

Lobef
Label control
, textbox control. '
Caption, control Frame.

? V It uaJ DomInlJt Se tup 1!!I~13

: Visual Dom inus Professional


Verson 1.00

. <:_) 1"'" '" Poseidon

. 9.2. Label controIs .

control.

- - - - - - - - - - - - - - -

-
.-
150 - - - - - -- - - - -- - - -

Alignment 3 :
- Left Justify ( )
1 - Right Justify ( )
2 - Center ( )
AutoSize rue . False control

WordWrap rue. False control


, (caption) '
Label control:
Pr i vate Sub Form-Load ()
Dim Authorl . Quotel As String

Label l.Aut oSize = True ' ~ o ll 6 AutoSize.


Label l . WordWr ap = True ' l l 6 Wo rdWrap.
Qu ote l = ~I co u l dn ' t wait f or succes s , 50 went wi t ho ut it . "
Author l = ~ - Jo n athan Winter 5"
Labell. Caption = Quot e l & Chr$ (10 ) & Authorl
End Sub

Opttonbutton
button button, (
(group) ' .
Alignment button
( 9.3.). , Caption ,
, Value, design .
Tnue False, button ,
, Click.

. 9.3. 1 butlons .

. 9.4., group
9 buttons. ,
control ,
. , (Index) , 8.
- events. DblClick button
. :

Pr i vate Sub Mtype-DblCl ick (In dex As I nteger)


rf Mt ype ( I nd e x ) .Va l ue The n
Msg Bo x ~n l ~ o ~ & St r $ ( Index) & ~ op t ion "
End !

--
End Sub

1 51
r -

.... I"st~.
OPTlONS EJ
n 30ption


11

. 9.4. 9 buttons, .

button "Ok" ,
:

Private Sub CornmandL-C li c k ()


Fo r i = 8
If Mtype( i). Value Then tmp i : Ex i t For
Next
MsgBox ~ E~x nK & Str$(tmp) & op t i on ~

End Sub

buttons group, button True.


buttons.

CheckBox
control button, .
button controls .

P' ~~~

r:.Check2
. 9.5. checkbol controls. l, '

Alignment Caption, controI,


Value :

CheckBox (default ) .
1 CheckBox .
2 CheckBox ( Grayed).

--
1 52
, , Click (
Run lime .

HstBo x
LislBox control ComboBox
m
conlrol, .

..
NewOrleMls ~
,
SI'IFrllci$CO
COC"9Q
S eltle :...
oorl o ::.J

. 9.6. , box .


Irol' Columns lisl box (scrolls) .
liSI box ( . 9.6), ,
Iisl box / ,
(. 9.7.).

oni:n9 makhs.1db pasIeI.dib

F;:'kIbof.Idb
_khs.1db
n<ti h t . mdb
eIolIL'xl
pe rIo rm.txt
tfj1:r;;y; i_,ainbow.dib
~.:rnal. txt
ernaIxt ~Kng. anboW.b
!mainfrm .lrm packing .lst re.w me.txt
mamfrm.frm pasteJ.dib re adme.ixi


. 9.7 list box .

ListCount (ilems) ' Ilst box


read only Run - time , :

Text! . t e x t = ~x~ & Li s tl . ListCount & items ~o li st box n

m Item, Listlndex
. ~em . read- wite Run - time
-1 lisl box ilem.
item, List.
, :

Li stl. List( O)

item list box, Lis11 . item


, :

Li stl. Li s t (Lis tl. Lis t Index )

MuItiSelect item
(Multiple - Selecbon lisl box). :

--
1 53 - - - - - - - - - -- - - - -

(Default).
1 . click Spacebar items list box.
2 Shift + click Shift + items. C~ + cl i c k
.

... Fo rml ,,~a

Visual Oominus4.0 1
Yisual Dominus 4.02
. ,
f s u al Dominus4.0 4.
V s u al Dominus4.0 5
. ,

Visual Oominus 4.0 7


;; . :
Vs ual Oominus 4.09
Vsu 81 Dominus4.0 1
" .

VIsual Dominus 4.0 12


V al Dominus 4.013

. 9.8. MulIiple . Selection list box.

Items Multiple - Selection


list box ' . Selected,
item list box, True/ False:
Pr i v ate Sub cmdTransfe r_ Clic k ()
For n = Li s tl.ListCount - 1
If List l .Selected ( n ) = True Then ' x~ 1 item
List 2 .Addlt em List l . Li st (n ) , li stb o x
End If
Next
End Sub

Sorted True, .
,
list box control.

Addltem ~em list box Run - time .
l:

lis t box.Addlt em i t e m i nde]

item , index ~em


. Clear Iist box :
l i s tbox. Cl e ar

, , Removeltem Item list box. " :

listbx . Rem oveltem index

--
1 54 - -- - - - - - - -------
CornboBox
Combo box control text box Iist box,
control. item text box
list box.
ListCount, List, Listlndex, Sorted, ItemData Newlndex,
Style combo box. ,
:

(Default) Dropdown Combo.


text bo list box, item -
text box list box, .

1 Simple Combo.
tet box list box, list box .
2 Dropdown List.
list box, .

Iist box, Addltem, Clear Removeltem.

IR~l
not No~
Chdrdonn~y _ - combobox (Slyle )
FumeBlanc
G ewi.zIr.!l mne
ZrJandel

.. Simple bo){ (SIyle 1)


I F~e Blanc_ .::I

J Chardnn.:'' J
Pin N or DropdoWfl kst ( S!yle 2)
,
Fme BI-!lnc
Gel'lirZra miner
Znfardel

. 9.9. SIyles Combo box.

, , Screen.
, . ActiveControl
controI events. ,
,
text box controI caption labeI controI .
P r i vate Sub Forrn-Click ()
If TypeOf Sc reen. Ac t i veCo ntro l I s TextBo xThen
La b el l .Caption Screen . ActiveCont rol . Text
El s e
La be ll. Capt i on "B ut ton: " + Screen. Activ eCon t rol. Ca p t i o n
End I f
End Sub

-
.-
155
ActiveForm events.
, captIon :
Private Sub CommandL-C lick ( )
Screen.ActiveForm.Capt i on = ~New Tit le"
End Sub

FontCount (fonts) ,
Fonts . list box
fonts :

Sub F o~Click ()
For = Screen.FontCount - 1
List l.Addl tem Screen.Fonts ( )

Next

End Sub

, combo boxes Font.Name Font.Size


4 check boxes caption
label control.

Fonts
~8 old N~.
..s Serif J
rIIalic
" J
S ize
-;
rUnde li"e

p ~I~!!~~

Demo
lr:J

. 9.10. .

Combo.Frm:
Deflnt -

, O X ~K cornbo b o x e s

Pr i v at e Sub Fo r ffi-Loa d ()
Dim i As Intege r

For i = 1 Screen.FontCount - 1
c omho l .Addltem S c r e e n . Fo n t s (i )
Next
combol . Listlndex =

--
1 56
comho2.Addltem "8.25"
comho2 .Addltem "9.75"
combo2 .Addltem " 12"
combo2 .Addltem " 13.5"
comho2 .Addltem "18"
combo2 .Addltem "20"
combo2.Addltem "24"
combo2 .List lndex =

check 1. Value = 1
End Sub

~~ ~~6n Value 4 check boxes ,

~ ~ ~ 6 n label contro l

Private Su b Checkl_Click ( )
l ab e l l 0. Font. Bold = che ckl.Value
End Sub

Private Sub Check2_Click ()


labell0.Font.ltalic c heck2 .Value
End Sub

Pr ivate Sub Check3_Click ()


labell0. Font. Unde rline chec k3 .Value
End Sub

Private Sub Check4_Click ( )


labellO. Font . Strikethrough check4. Value
End Sub

lv l item combo bo xes, -

K~ l ~~6 ~o label control.

Private Sub Combol~Click ()


labell0. Font. Name = combo1 .List (combo1.Listlnde x)
End Sub

Private Sub Combo2_Cl ick ()


labell0. Font. Size= Val(combo2 .List(combo2.Listlndex
End Sub

Private Sub Command3_C l ick ()


Unload Me
End Sub

ScroH Bc r5
(Scroll Bars) controls HScrol18ar VScroII8ar
COX. ,
, .
vj multiline tet boxes list boxes controls,

--
, , .

1 57
.. FOfml I!!lOOI3
...
... '[j"
.. .. . .
. ..

. 9.11 . (HScroIIBar) (VScroJlBar) .

Min m .
defaull .

Max .
defaulf 32767.
Value
min max.

Change click OV-


U .

Scroll .

scroll bar
' label control:
o~ Form-Load Scro l l Ba r
KQl ouvtXE1Q Di s pla y Da t e ~

Pr ivate Sub ForL..Load ()


HScro l l l.LargeChange 5
HScrol l l.Mi n 1
HS c r o l l l . Ma x 30

Di splayDate
End Su b

e vent Ch a n g e ~ .

Di s p l a y Da t e .

--
Priv a t e Su b HScro l ll_ Change ()

1 58
DisplayDate
End Sub
~ VB Now Kal
n Scroll Bar cont ro l ,

. caption label
.

Pr i vat e Sub Di splayDate ()


Dim TimeVa l As Va r i ant
TimeVal = Now + HScrolll.Value
Labe!l. Caption = Format (TimeVal, "dd / mm/ yy " )
End Sub
Scroll.Vbp, ,
text box control. 80 RGB.

Forml I!lIiIEJ

. 9.12. text box control.

event Scroll contro ls DoCo lo r

Private Sub hs bBlu6-Sc r ol l ()


DoColor
: d Sub

? r ~ v a te Sub hsbGree-S croll ()


: c C l r

:-. Sub
?= ~ va ~ e Sub hsbRed-Sc ro l l ()
DoColo r
:: Sub

~~ , event Change co nt ro l s

OL~iva Sc r ol l control.

?=iva~e Sub hsbBlue-Change ()


hsbBl ue-..Sc r ol l

--
::::: S:lb

1 59
Private Sub hsbGree~Cha nge ()
h s bGr e eILS c roll
End Sub

Private Sub hsbRed-Change ()


hsbRed.-S cro l l
End Sub

1 1 1 1 1 Value 1 scr o l l bars


KQl RGB 1 1 1 Ba ckC o lor text box.

Pr i v a t e Sub DoColo r ()
t xtColo r . Ba c kColo r RGB( hsbRed. Value, hsbGreen. Value,
hsbBlue . Val ue)
End Sub
,
text box control . Move
controIs.
Priv a t e Sub Form-Lo a d ()
HSc rolll .Ma x 100 \ 1 1

Text l .Left = \ 1 t e xt box 1

End Sub

\ t ext box sc r o l l bar.

Priv a t e Sub HScro l ll_Change ()


Text1 .Le f t = HScro l 1 1.Value * 10 0
End Sub

Hle - SY5tern COJltrol5


Visual Basic controIs drives,
directories . controIs drive Iist box, directory Iist box fiIe Iist
box. .

O.,ecIorylis I b OJ: -

. 9.13. drive Iislbox, direclory lislbox fiIe Iislbox controls.

Drtve H5t
drive Iist box controI Iist box (drop-down)
drive . , , drives
' .

--
. 9.14. drive Iislbox drives .

1 60
drive Drive, :

Dr i v e l .D rive = ~ C : \n

Drive, control de.


ChDrive, :
ChDr i v e Dr i ve l.Dr i v e

Change de .

Dtrectory Hst
directory list box control d rec t es () d e .
directory

sJex - 2

~c:\

!..J hc
O -dde
Doch
D,_ LsIrx:l -
D""",,,
D-
D ..... !J
. 9.15. directory listbox directories.


control ListCaunt, Listlndex List controls lisbox
combobox. 9.15., (
) Listlndex -1 .
,
-2 .
ListCount .
,
9.15., 7 (hc, ... ,winapi):
Privat e Sub Di r l-Cha ng e ()
Di m c n As Intege r

Cl s
For c n = d i r l . Li s t Count - 1
Pr i nt d ir l . Li st (cn )
Next
End Sub

' cl Change,
. Path,
. ' De cl, Ghange:

--
1 61
Private Sub Dr ivel-Change ()
d i r l . Pat h = dri ve l.D rive
End Sub
control ,
ChDir.
ChDir Di r l . Path

Hfe Hst
file list box control ' Path,
, design
.

. 9.16. file st box .

Pattern
(extensIon), .FRM . BAS.
Fi le l . Pattern = "* . FRM; *. BAS"

Visual Basic wildcard.


D , MultiSelect
True, Selected ( Iist box control)
.
Archive, Hidden, Normal, System ReadOnly fileIist box
(file attributes), True False.

[form. ] fi l elist bo x. Ar chi ve [ = boo l e an ]


[ f o rm. ] f i l e li stbox. Hidden[ bo olean
[f orrn. ] f ile list bo x. Normal [ = boo l e an ]
[ forrn. ] f ile l i s tbox. Syst em[ = boo l e an ]
[ f o rm. ] f i l elis t bo x. ReadOnly[ = boolean

' ,
SetAtlr.
' directory list box control, Change,
' Path file list box:
Privat e Sub Dir l_Change ()
f i l e l . Path = dir l .Path

--
End Sub

1 62
ListCount, Listlndex List.
' file list box control:
For i = Filel ist .Li stCount - 1
Print Fi le l i st. Lis t ( i )
Ne xt

, PathChange Path control,


PatlernChange Patlern.

Hrner
timer " " control, Run time
.
Timer.

. 9.17. timer C I'

lnteral , milliseconds (
) Timer. 65535.
( controlS) able , control.
lanm. b
alanm.

118:42:56 JI
AlJflll SeIIir : r AlwIII !

. 9.18. .

buttons timer, m
caption Iabel
text box , L.
:

, A o o ~ o 1 timer

Pr i v at e Sub Form-Load ()
timerl. Enabled = Fal s e
End Sub

op t ion b ut ton 10 c ont r o l.


1 ( I ndex = ), a O0 10

- -- - - - - -- - - - -
--
16 3 - - - - -- - -- - -- -
t i me r , ~ o ( I ndex 1)

Pr iva te Sub OnOffBu t to-Clic k (Index As Intege r )


I f Index = 1 Then
t ime r l .Enabled Tr ue
El s e
t i rne r l . Ena b led False
End I f
End Sub

t i me r ~ 10 0 0 mill i se c onds capti o n


labe l .

"Ti me $ > Alar.mSett ing .Te xt"


K~ x ~ ~ Tr ue
K~ , o ~ Be e p .

Priva t e Sub Time r L-T ime r ()


Disp l a y .Capt ion = Time $
I f Time$ > AlarmSet ting.Te xt Ad
Tr im$(AlarmSetting.Te x t ) <> ~w The n
Beep
End I f
End Sub

Im1l0e
Visual Basic controIs
,
GIF, JPEG, Bitmap, Icon MetafiIe.
ImagecontroI, controls, Picture,
design ,
LoadPicture, :

Pi c t u r el. Pi ctu re = LoadP ict u re { ~ico ns \comput e r \tra s h02a . ico#)

, Image controI , :

Pi c t u r e l .Pi c t u r e = P i cture2 .Picture

HJ'IItj , ;

--
. 9.19. .

1 64
Stretch,
True False
, control.
Image.vbp , icon
, click ' , timer.
check box,
Image.Frm:

Option Explici t
Dim I mg W

v i mage control
KQl v .

vQ v

KOl t i me r.

Private Sub Form-Load ()


Imagel .Picture = LoadP icture ("a rw02 rt . ico" )

I ma g e l . Left =

I mg W = Imagel.Width
Timerl . Interval = 300
Ti me r l . Enabl e d False

Checkl.Caption "S t r e t c h Property"


End Sub

, 6Xl i ma ge control

Private Sub Check l-Click ()


Imagel . St retch = Checkl .Value
End Sub

\ tirner

Pr i vate Sub Fo rm-Cl i c k ()


Time rl. Enabled = True
End Sub

, v 6Xl image control

Private Su b Time r l _ Time r ()


Static Movelcon As I nt e g e r

I f Not MovelconThen
Imagel .Move Imagel. Left + ImgW, Imagel .Top, ImgW * 2
Else
Imagel .Move Imagel. Left + ImgW, Imagel.Top, ImgW
End I f

If I ma g e l . Le f t > ScaleWidth Then


Imagel.Left =

Timerl.Enabled = False

--
1 65
End !
Move l con Not Move lcon
End Sub

image control
button toolbox.
image control
( down). image
Padlock ' LockOpen LockClosed, Load
:

Pr i v ate Sub F o rm.....Lo a d ()


Pa d lo c k.P i c t u r e = Lo ckOpe n. Pictu re
End Sub

, Click Padlock image :

Priv at e Sub Pa dl o c k-Cl i c k ()


Stat i c Lo ck e dFlag As I nt e g e r
If Loc ke dFlag Th en
Pa dlo ck .P icture LockOpen.P i c t ure
El se
Pa dlock.P icture LockC losed.P icture
End I f
Locke dF l a g = Not LockedFl ag
End Sub

LockedFlag, Padlock image.

Ptc:tureBox
control Picture ; image control,
, Line, Circle, PoInt, Print . . , .
, Circle '
pIcture box:
Pi c ture l .Auto Redraw = True
Pictu r e 1. Ci r cle (1200 . 10 0 0 ) r 750

AutoRedraw , pIcture
box .
, control , . ,
, image pIcture box control,
.
Picture,
" " pIcture box, . ,
Picture, '
ture box:
Di m obj Pi c As Pi c tu r e
Set ob j Pic = LoadP i ct ure (UButt e rfly.bmp" )
Se t Pict u r e1 .Picture = o bj Pi c

--
1 66 - - - - -- - - - - - - - - -
St11.e
Shape ,
, , . . , Circle, Line . .
Shape,
, Shape.Vbp, controls
Shape control .
. controls, time .

l Sha pe 11iI]

(' S he IO

8
('"Shape 11

r.:;; hape .~

r s h.e 13

r Stupe 14

r 5hae.5

. 9.20. control Shape.

, , button (index) .
, , Load control,
, , :

Fo r = 1 5

Load Optionl ( )
Ne x t

5 button, 1 . control
Load, Unload:
UnLo a d Opt ion l ( 3 )

,
' option button , . . 1 _Click.

Private Sub Opt ion l-Cl ick (Index As I nteger )

Shape.Frm.
Option Ex pl ici t
n~o 5 op tion button
Optionl 1 16 1

. c a pt ion

1 Visible .

, 16

Fi l l Style Fi l l Co l o r , shape

--
1 67
Private Sub Form....Load ()
oim

Option 1 (O ).Ca ption Shap e ,


For "" 1 5
Lo a d Opt ion 1 ( )
Opt ion l ( I ) . Top "" Opt ion1(I - 1 ) . + Opti on1(0 ).Height + 4 0
Opt ion1 (I ) .Capt i on ~Shape *" &
Optionl (I ).Visible "" True
Ne xt
Shape1.Fi llStyle

Shapel. FillColor RGB( 255, , )

End Sub

1 c on tro ls 1

Shape cont ro l

Private Sub Op t i o n 1_C l i c k (Index As Integer)

Sh apel .Shape "" Ind e x


End Sub

LJIe
, l ne control
, . 1, 1 ,
control, BorderWidth .
Line.vbp , line bmer
contral. ( click ) , line.
Line.Frm:

Opt ion Ex pl i cit

1 timer 1 1 n 1

\ .

Private Sub Form-Cl i c k ( )


Ti mer1.Enabled"" True
End Sub

, 1 1 timer 1 1ine c ontrol.

Pr i v a t e Su b Fo rm-Lo a d ()
Timerl . I nterval = 1 0 0

Line1 . X1 100
Line1 . 1 10 0
Li ne 1. 2 500
Line1. 2 300
End Sub

timer 1 (animation ) l ine c ontrol.

--
1 68
Private Sub Timerl_T imer ()
St at ic Odd

If Odd Then
Linel . 2 Linel. 2 + 250
Linel .Y2 Linel . 2 + 600
Else
Linel . Linel.Xl + 250
Linel.Yl Linel.Yl + 600
End If
Odd "" Not Odd

If Line l . Yl > Sc a l eHe i g ht Then


Time rl.Enabled "" False
Linel. 10 0
Linel . Yl 10 0
Linel . 2 500
Linel. 2 3 00
Odd = Fa lse
End If
End Sub

ScaleHeight
, ScaleWidIh ( ) .

Dfj t fj -
conIrol, (MSAccess ) ,
. L control.

CU5torn ctrl5

controls Viusal Basic,


OCX. , OCX
(DLL). controls. custom controls
, C++
Studio Microsoft.
OCX ,
Visual Basic.
System Windows. Windows,
Registry. .
OCX ,
System , Dos prompt REGSVR 16-bit OCXs
REGSVR32 32-bit OCXs ( 5.0 32-bit
4.0). :
REGSVR32 C: \WINDOWS \SYSTEM\CUSTOM.OCX

Visuai Basic ( ) .

--
, Registry

1 69 - - - - -- - - - - - - - - - -
REGSVR ( REGSVR32), :

REGSVR32 / C: \WINDOWS \ SYSTEM\ CUSTOM. OCX

custOJJJ slJ1: GS C
custom controIs,
ViusaI Basic.

CommonDiaIog
CommonDiaIog controI, ,

, 5 .
:

,
.

Save n ,
caption .

Print
.

Color , .

Font , ; .

control , Act o n,
,
.

[ f o rm. ] CMD i a l og. Acti on[ = setti ng ]

setting .

2 Save
3 Color
4 Fonl
5 Printer
6 WINHELP.EXE

ShowColor, ShowOpen, ShowSave, ShowPrinter, ShowFont


ShowHeIp, AcIion.
CancelError, ,
CanceI button. True False.
[ f o rm. ) CMD i al og. Can c elEr r o r[ = {True Fa lse} ]

--
1 70
DiaIogTitle, caption
titIe bar .

[fo rm. ]CMDialog .DialogTitle [ = t itle ]

read, .

11.. .llHIl
i1
_!D1X. .,1
. - . . ~- .
.,... ....

..............
,

- . ... . - . .
- - - -
. ,

,"' "
_
.

0 . 0 .

. 9.21. CommonDialog control.

, Dialogs.Vbp,
' CommonDialog control moduIe, Dialog s.Bas,

5 , control.
declaration module:

Deflnt -

Type FontProp
Fo ntName As String
FontSiz e As Single
Fo ntBold As Integ er
F o tl t a li c As !nteger

FontUnderLine As I ntege r
FontStrikeThru As I nt e g er
ForeCo lor As I nt e g e r
End Type

FontProp , module.
FiIeSelect Open, Action 1.
DefaultExt (etension) , . . .. FiIIer
Type . :

CMDialog. Filter[ = des crl Ifilter l Id e s c r 2 Ifilter2 . . . ]

*., tet.
, ": " (ASCII 124) .
,
tet picture, bitmaps icons.
Text ( *. t x t ) 1*.txtIPictures (*.bmp; * . ico) I*.bmp; * . ico

Filterlndex default , FIags


Open Save. , OFN_FILEMUSTEXIST,
,
. , Filename ~ .

171

-
.-
FileSelect, , , path$,
( *.), titie$,
. :

Function File Se lect (path$ , tit l e $ ) As String


dialogs.CMD i a l ogl. CancelError = Tru e
Loca l Erro r GoTo end2

dire $ = Cu r Di r $: dire $ = Left(dire $ , 2)


dia l ogs. CMDial ogl. DefaultExt = p a th$
d ia l ogs . CMD ia l og l. DialogTitle = t it le$
dia l ogs . CMD i a l og l .Filename = -*. + pat h$ W

d i a l og s . CMD i a log l. Fi l te r = -* . W + path $ + Chr$ ( 124 )


d i a l ogs. CMD ialogl. Fi l t e r l nde x = 1
d i a l ogs. CMDi a log l . Flags = cdlOFNFile MustEx is t
di al ogs . CMDialog l .ShowOpe n
ChDr i v e di r e$

Fi leSe lec t = d ialog s . CMD i a log l. Filename


Exit Function
end2:
FileSele c t = ~H:ChDri ve di r e $ :Exit Fu nc t ion
End Function

f11e$ = FileSelect ( " * . " . " )

f 1 1e $ FileSelect ( "BAS" , " " )

v a IJEJ
Filej)le: [olde : 0<
111; c:\ vb4
add,ettb. E;j c :\
U ol.bp

bbIio. 1db
biblo. mdb
.,:,) hc
bright. dib D include
dataag .ece ZJ odbc fl.e ad onIy
dosecp. zp CJ repot
11 aia dal

. 9.22. la Open.

FileSave .
ShowSave, Flags cdIOFNCreatePrompt

--
cdlOFNOverwritePrompt. -

1 72
.
,
(ov erwrte) . 10
.

Func t i on fi l e s ave $ (pat h$. tit l e$ )


di a l ogs.CMDia logl .Canc e l Er ror True
Lo c a l Error GoTo endl

di re $ = CurDir$: dire$ = Lef t( dire $, 2 )


di a logs .CMDi a log l.D e f au l t Ext = pa t h$
d ialog s .CMD ia logl. Di a logTi t le = tit l e$
di a l ogs .CMD ia logl . Fi l e name = ~w
I f pa t h$ = ~w Then
dia l ogs. CMD i alogl.Filter ~ * . *w + Chr $ ( 12 4 )

Else
d i alog s . CMD i alog l . Filter ~ * . W + path$ + Chr$ ( 124 )

End I f
dialogs. CMDial ogl.Flags = cdl OFNCreatePr ompt Or cdlOFNOverwritePrompt
di alogs.CMD i alogl.ShowSave
ChDr i ve dire$
f i l e s ave = di alog s . CMDi a log l . File name
Ex it Func t ion
e ndl :
f i les ave = : ChDrive dire$ : Exit Func ti on
End Func t i on

fi1e$ = f ilesave$ ( "FRM" r " . " )

GetPrinterlnfo Printer, ShowPrinter.


, FromPage, ToPage Copies
. .
m Cancel button, -1, :

Func t i on GetPrinter lnfo (Be g i nPage, EndPag e , NumCopie s)


dial ogs. CMD ialogl . CancelError = Tr ue

Loc a l Error GoTo end3


dialog s . CMDialogl .PrinterDefault = True
d i alog s . CMDialog l . FromPage = BeginPage
dial ogs. CMDialogl. ToPage = EndPage
dialog s. CMD i a l ogl . Copies = NumCopies

di a l og s. CMDial ogl. ShowPrinter


Begi nPage = dialogs. CMDial ogl. FrornPage
EndPage = dia l og s . CMDi alog l . ToPage
NumCopies = di alog s .CMD i a log l .Copies
GetP rint er ln fo = : Exit Funct i on

--
e nd3 :

1 73 - - -- - - - - - - - - -- -
Ge tP r int e rlnfo = - 1: Exit Function
End Funct ion
:
ret = Ge t P r i n te r l n f o ( 1, 3, 5)

PrInt 1JE3
Pnl III: Default (lexmak QK
1 : )

nl range===~~==rr,
o~ :ietup...
r S~Il!!Ction
: fage;

"'~' E:::J 100 E:::J


Pnl ~Iy: lliign ::J toie;: ~
r:: Pin 10 fi!e r: CoHale c op!e$

. 9.23. Printer.

GetColor Color, ShowColor.


long integer -1 , Cancel button.
Function GetCo lor ( ) As Lon g
dialog s .CMDialog1.CancelEr ror True

Loca l Error GoTo e n d 4

dialogs .CMDialog1. ShowColor


GetColor = dialogs.CMDialog1.Color
Exit Function
end4:
GetColor = -1: Exit Function
En d Function

color & = GetCo lor( )

.i r r r r r;;i r r
. r r r r .D liiI &:I
.r:; rliiI . .i . 1iii
. r-

I!!!J .
t:u. ~"", colo .:

~~~~ fi~:~ B~
;;;r r.;; r;;i ffii
liliH II
\)~!~ ."."", ,,,,lnno > ColO1S!!lid : ~ BIye: [Q
odd Dmom CI<ii.

. 9.24. Color.

--
1 74
GetFontlnfo Font, ShowFonI.
FontProp
FontName. , !
. Gance[ button,
-1, .

Funct i on GetF ont I nfo (font As FontProp)


dia l ogs.CMDialogl. CancelErro r = True

Local Error GoTo end5


f ont .FontName dialogs . CMDialogl . FontName
f o nt. FontS i ze = dialogs . CMDial ogl. FontS ize
font.FontBo ld = d i alogs. CMDial ogl . Fo ntBol d
font . Fo nt l t a l ic = dialogs. CMD i a l ogl . Fontltali c
f ont . Font Unde rLi ne = dialogs . CMDia logl. Font Unde r Line
font . FontSt r ikeThru = dialogs. CMDia log l . Fo ntSt rikeThru
dialogs . CMDialog l . Flags = c dlCFBoth
f ont.Fo reColor dia l ogs.CMDialogl .Sho wFont

GetFo nt l n fo r =

Exit Funct i o n

e nd5:
GetFontln f o - 1: Exit Func t ion
End Funct ion

Dim f ont As Font Pr op


fo nt. Fo nt Name = "Co urier H
r et = Ge t Fo ntl n fo (font )

Fonl 613 1
Fort .!e:
IR_ 0<
~

.=J
s_ .=J

$q:ipt

--
. 9.25. Font.

1 75 - - - - - - - - -- -- -- -
, ShowHelp WinHelp.Exe.
:

Private Sub Help-Click ()


\ Help

CMDialogl .HelpFile = App.HelpFile


CMDialog l.HelpCornmand = cdlHelplndex
CMDialogl. ShowHelp
End Sub

MSChart
MSChart control .
, , design
. MSChart control
.
. , ChartType
. MSChart control
DataGrid , ,
control .

100 100

-1
6ll +-- - - - - 6ll

40 - -' - 40

20 20


RI R2
'- r
R3 R. R5

. 9.26 . S C h a conlrol, .

DataGrid
, ColumnCount RowCount
. ColumnLabelCount RowLabelCount
labels , Column Row
DataGrid. The ColumnLabellndex RowLabellndex
labels. , ColumnLabel RowLabel
label .
, bar chart,
labels:

Pr iate Sub Cornmandl_Click()


Dim r o wLabelCount As I nt e g e r
Dim c o lumnLabelCount As Integer
Dim rowCount As rnt e ge r

--
Dim columnCount As Integer

1 76 - - - - -- - - - -- - - - -
Dim Dat aGrid As DataG r id

Set Da taGrid = MSCha r t 1. Da t a Gr i d


, bar cha rt
MSCha rt1. cha rtType = VtChChartType3dBar

With MSChart1.DataGrid
Da taGri d .

r owLa be l Co u n t = 2
columnLabelCount 2
rowCount = 6
columnCount = 6
' KOl 1abels
. SetS ize r owLabe l Co u n t, columnLabelCount,
rowCou nt , columnCou nt

'

RandomDataFill

' labels .

Dim labe l l nde x as Integer


Dim column as Integer
Dim row as Integer
labellndex = 2
' l a bels

column = 1
ColumnLabe l (column, labellndex ) "Product 1"
column = 4
.ColumnLabel(column, labellndex) "Product 2"

row = 1
' labels

RowLabe l( row, l abe l l n d ex) "1994/1


row = 4
. RowLabel(row, labellndex ) '1995"
End with
En d Sub

MSChar1 control Char1Data,


DataGrid , :
Dim ( 1 3, 1 3) As Variant

'

Fo r i = 1 UBound 3
For j = 1 3
(i , j ) = i * j
Next
Next

'
l abel s .

( 1, 2) "Wheat"

--
( 1, 3) = "Corn"

1 77
' labels .

( 2 , 1) "Januar y"
( 3, 1) = "Februa ry"

' .

MSChart1

' v a r i a nt .

= MSChart1

' ~

For i = LBound (Y, 1) UBound (Y, 1)


For j = LBo und ( Y, 2) UBound(Y, 2)
Pr int Y(i , j)
Next
Ne xt

GhartData default MSChart contro1.

MSComm
MSGomm communication control
/ . m
, ; downloading uploading,
termina1.
,..--- - - - - - - - --,

rue
Flse
cornNone
,02.

. cornltMode ext
600
/JI'd FIse
BoiferSle 512
/JI'ityRelace ?
..""",

SEn.!tIe FIse ..:J

. 9.27. MSComm control .

MSGomm control , CommPort,


, PortOpen .
, Settings , baud rate . .
:

CornmCtrl.CornmPort 1
CommCtrl.Po rtOpen True

--
CommCt r l . Set t i ng s "192 0 0, , 8 , 1"

1 78
, , ll
.
,
' modem:
A~ 1 K6 10 1 0 .

Di m I nstr ing As St ring


\ 1 1 0 COMl .

MSComm l .CommPort = 1
, 96 00 baud, parity, 8 data, a nd 1 st op b i t .
MS Comm l .S e t tings = " 9 6 0 0, , ,l

, c o nt r o l 6 1 10 10

, .
MSComml . I nputLen =
\ .
MSComml . PortOp e n = True
\ . ( at t e ntion command ) mode~

MSComml .0utp ut = " + v bCr

, 1 V10 . 1
\ '''" .

00
DoEvents
Loop Unt i l MSComm l . InBuf fe rCount >= 2
Instring = MSComml. Input
, .

MSComml .Por t Open = Fa l s e

let box conlroi


lerminal. KeyPress, :

Pr iva t e Sub ermina Wi nd w- eress (es c i i As I nte g er )


! CommCt rl . PortOpe n Then

CommCtrl. 0utput : Ch r $ ( KeyAscii )


KeyAsc ii :
End !

End Su b

conlrol , OnComm, " "


( , "" ..) . ,
tet box conlrol ,
MSComm control:
Pr i v a t e Sub CommCtr l-OnComm( )
Er r o r Resume Next

Di m Cur s o r Pos , EVMsg$

Se le c t Cas e CommCtr l .ComrnEvent


Case v bMSComrnEvSend

--
17 9
Case vhMSCommEvReceive
Term inal Txt = CommCt rl. I nput
Curso rPos = Len(Termina lWi nd ow.Text)
Termina lWindow.SelStart " = Curso rPo s
' ~~ x 1 ~ BackSpace

If InStr (Terminal Txt , Chr$ (B ) ) Then


TerminaIWindow.SelSt art = Cursor Pos - 1
Term i nalWindow.SelLen gth = 1
TerminalTxt = Mid$(TerminalTxt, + 1)
End If
TerminalWindow.Sel Text = TerminalTxt
If Captur eOn The n
CaptureBuf = Ca ptureBu f + Te rmin alTxt
End If
Ca s e vhMSCommEvCTS
EVMsg $ = ~C h ang e in CTS De t e ct e d "
Case vhMSCommEvDSR
EVMsg$ = ~C h a ng e in DSR Detecte d "
Ca s e vhMSCommECD
EVMsg$ = ~C hang e in CD Detected"
Ca s e vb MSCommEvRing
EVMs g$ = ~ T he Phone is Ringing"
Ca s e vbMSCommEvEOF
EVMsg$ = ~End of File Detect ed"
Error me s s a ges.
Case vbMS CommErBreak
EVMsg$ = ~Bre ak Received"
Ca se vbMS CommEr CTSTO
ERMs g$ = uCTS Timeout"
Cas e vbMS CommErDSRTO
ERMs g $ = ~ D S R Timeout "
Ca s e vbMSCommErF rame
EVMsg$ = ~ Framing Er r o r"
Ca s e vbMS CornmErOe rrun
ERMsg$ = ~Oe r ru n Erro r "
Ca s e vbMSCommErCDTO
ERMs g$ = ~Ca r ri e r Detect Timeout "
Ca s e vbMS CommErRxOer
ERMsg$ = ~ Re ce ive Buf fe r Oerf lo w "
Cas e vhMSCommErRxParity
EVMsg$ = ~P a r i t y Er r o r "
Ca s e vhMSCommErTxFull
ERMsg$ ~Transmit Buffer Fu l l"
Cas e Else
ERMs g $ ~o 6"

End Sele ct
End Sub

--
( ) terminal.

1 80
SSTab

SSTab Diatog control tab control OptIons Microsoft Word
Excel. tab controIs. , tab,
Tabs tabs, Style
tabs, Word () property sheets
Windows 95 (1).

ConfIgure Anima

,~_-;) I."" I '....... 1


I neInet In

User lD
.. ~_ ..

PaUWOfd _
~

11'N ame '!'
.- --
...
Serv ers

Newr.


j

Inl ernet MJ
E-mail 1__
H e3de r. ;;:

De lete fIom Servel' Ii'"

11'
~ f;.dnCfJI !

. 9.28. Tab conIrol tabs.

Microsoft MaiI
(e-mail) Microsoft ( )
, e-mail Internet,
Fax . .
,
Mail Serers , MIcrosoft Mail, MicOsoft Exchange,
Novell's Group Wise, Lots cc:Mail . ,
controls,
MAPlsession MAPImessage. MAPlsession control
Microsoft Mail sere r. ,
. Signon
Signoff . :

MapiS ess.SignOn
! Er r <> Then
Ms gBo x ~H Logon 11 : ~ + Error$
Else
Map i Me s s . Se s s i onI D MapiSess. SessionID

--
End !

1 81
MAPlmessage
Mail serer. control :

Compose .

Copy ' .

Delete .

fetch .

Forward .

l .

Send .

MsgGount
Caption :

Screen.MousePointer = 11
MapiMess.Fetch
Caption = ulnbox - u + CStr(MapiMess.MsgCount) + U "

Screen. MousePointer =

FetchUnreadOnly True,
FelchSorled, .
,
listbox control (
MsgOrigOisplayName), ( MsgSubject)
( MsgDateReceived) . MsgRead

Msglndex:
Dim read As Boolean, As Integer
Listl. Clear
For i = mailctl.MsgCount - 1
mailct l .Msglndex = i : read = True: Mess$=""
If Not mailctl.MsgRead Then read = False: = + 1
a$ = Format$ (mailctl. MsgO r igD isplayName, "!" + String$ ( 1 0, "@")
If Not read Th e n
Mess$ "*" + " " + a$
Else
Mess$ a$
End I f

If mailctl.MsgSubject <> "" Th e n


Mess$ "" Mess$ + " " + Format$ (mai lct l. MsgSubject, "!" +
String$ (35, "@"))
Else
Mess$ = Mess$ + " "
End If
Mess$ "" Mess$ + " " + mailctl.MsgDateRece ived
Listl.Addltem Mess$

--
Ne xt i

1 82
Caption = ~ Y 6 xo ~ + CSt r ( X) + ~ 16

, 1 , 1 1 0 1

MapiSess . SignO f f
If Err <> Then
Ms g Box ~H Logo f f 1 1 : ~ + Er ror$
End If

StatusBar
StatusBarcontrol '
, StatusBar
Panel, Panels.
, panel
. Add
Panel, :

StatusBarl.Pane ls.Add

9.29 Style
Panel StatusBar.
, . Alignment,
Panel, Text, Panel, Key,
.. Panel.

Sta tusBa r Control PropertIe s EJ

"", fl.!I!J
!ei<l:
r.y Ii-- - -
_ 10 .....
~",,' 10.T'"
~eveI: 11 ' lf'lSeI ~
"""~. I~I

0< =>< 1 -

. 9.29. StatusBar control.

3 Panels ' StatusBar control. ,


Date panel, , , Time panel, ,
:

Private Sub Form-Lo ad ( )


Dim As I nt e g er
For = 1 2
St a tus8arl .Pane l s .Add
Next

--
18 3
With Stat u s Ba r l .Pa ne l s
Item( l ). Sty l e : sbrDate
It em(l) .Ke y : -Date pane l-
I tem ( l ) . Au toS i ze : sbrConte n t s
Item(l) .MinWidth : 2 0 0 0
Item( 2) .Style : sbrTime
Item(2) .Key = "Time panel"
I t e m( 3) .Aut o S i ze : s b rContents
I tem(3 ). Te xt : "Miscellaneous Data"
Item(3 ).Key : " Pa n e l 3"
End With
End Sub

PanelDblClick Stat s8 ar,


' Panel Stat s8ar control. ,
Panel.
' .

Priv at e Sub StatusBarl-PanelDblClick (ByV a l Panel As Pa nel )


P rint Pa nel . Ke y & " Width = " & Panel.Width
End Sub

Panel Index, Panel,


Count, Panels ' Stats8ar control . .

ProgressBar
Progress8ar control ,
.

@l
. 9.30. Prog ressBar contro .

Max,
control Value .

Slider
Slider control ,
, , .

II, ... ~
. 9.31 . SIider control.
Max. ,
SelectRange. .

Imagelist
Im ageL st control controls,
, listlmage.

--
1 84
Wi1J!1' 'ei,iit.i. 41. iHII:l

. 9.32. .

,
9.32, control, Add
Listlmages, ,
:

Dim im g X As List Ima g e

Set ingX = Ima geLi s tl.


List lmages .Add ( , -ro cket , LoadP icture( -i c ons \indus try \ rocket . i c o


ImageList control:
Dim imgX As Lis tIrnage

Se t i mgX = I rnageLis t .L istlrnage s (3 )


, . l Key l ~third

Se t imgX = ImageLi stl .Lis tlmages(-third- )


It em

Set imgX = ImageList l.Listlmages . Item ( 3 )

, Extractlcon
bltmap ImageList controI. ,
M o use lco .

Private Sub Form-Load ( )


Dim im gX As List lmage
Set im g X Image Listl . Li s tImages .
Add( , , Lo adP ict ure ("bi tmaps \ asso rted\ba l l o on. bmpH
End Su b

Priva te Sub Form-Cl i ck ( )


Dim p icX As Pictu r e
Set p i cX = I ma g eLi s tl . ListIma g e s( l). Ex t r a c t l c o n

--
1 85
With Forml
. Mous elcon = p icX
. Mo u s e Po i n t e r = vbCustom
End With
End Sub

L stV iew
ListView control 4 ; .
, ,
. ' Listltem. View
ListView control, Large (standard) Icons,
Small lcons, List Report.
, Listltem ColumnHeader.
, '
ImageList control. Icons Smalllcons. ,
() SubItems. SortOrder
, Sorted
. ColumnHeader .
List.b , ListView ImageList controls.
ListView control View
combo box control.

11. _ l '

Ilcon J

. 9.33. ListView conIrol Icon.

Pr i v ate Sub Fo rm-Load ( )


Dim clmX As ColumnHeader

, ColumnHeaders
Se t clmx Li s tVie wl . Col umnHeaders.
Add( , ''Author'' , Li s t Viewl. Wid th / 3)
Set c l mx ListViewl.Co lumnHeaders. _
Add( , " Title " , Listviewl. width / 3)
Se t c l mx List Viewl.Co lumnHeaders . _
Add( , "Publisher" , ListViewl . Wi d t h / 3)

view 11 6 Report.
Lis tViewl .View = lvwReport

, o OU ' 1 10

--
ImageList c ontro l .

1 86 - - - - - - - - - - -- - - - -
Dim imgX As Listlma g e
Se t i mgX = ImageListl.L istlmages. Add
(, , Lo adP i ctu r e ( " i c on s \ Wr i t i ng \ No t e 0 6. ." ) )
Se t im g X = I ma g eLis t 2 .Listlmag es . Add _
(, , LoadPictu r e ("bitmap s \assorted \ w.bmp"

x~ o ~ Ima ge Li st controls ~o Li s t Vie w control.


ListViewl. I c ons = l mageLis t l
ListViewl .Small lcon s = Ima geList 2

With Combol
Addltem ''Ic o n ''

Add ltem "Smalllcon" 1


Addltem "Li s t " 2
Addltem "Report " 3
List lndex =
End With

\ ~ Lis tltem ~K - .

Dim itmX As List l tem

, Author
Set itmX ListViewl . Li s t l t ems. _
Ad d ( , " " , 1)
Ti tl e
itmX. Sub l t e ms (l ) = " o ~ 1 6 1 Wi ndows"

, Pu bl isher
i t mX.Subl t e ms ( 2) = "Anubi s "

, 1

Set i t mX = ListVi e wl . Li s t l t e ms. _


Add( , , "Wi 1 1 i am Gibson", 1)
i trnX. Sub ltems ( l ) " "

i trnX. Sub l t ems (2) = "Aqu a r ius"

Set itmX = Li s t View l . Listltems.


Add(, , " . " , 1)
itmX.Subltems (l ) " o ~"

itmX. Subltems (2 ) = " 1 "

End Sub

\ View 1 1 ListView cont rol .


Pr ivate Sub Combo L-Cl i c k( )
Li stViewl . Vi e w = Combo 1. Li st lndex
End Sub

RichTextBox
RichTextBox control textbox control . '
6 4 textbox.
RTF format, MSWord.

--
control ,

1 87
, ' , , ..

Here is text the RichTextBox -'.J


Suppo rts multiple:
Poi nt sizes
Fonts aIlII fon t styles
Colors
. -- - _. .J.:
. 9.34. RichTeIlBox C I .

LoadFile SaveFile
RichTextBox control, :

Pr i v a t e sub Comma n d l-Cl i c k ( )


CommonDialog l . Fi lter = "Rich Text Format f ilesl*. rtf "
CommonDialog l.ShowOpen
RichTextBoxl.LoadFile CommonDialogl.Filename, r tfRTF
End Sub

SelRTF RTF , SelPrint


. oo l bar control
.

oolbar
Toolbar control button.
. buttons
Add

~..ll fJ I
. 9.35. Too lbar control .

button oolbar control ,


ImageList control. Caption, Image.
controls Toolbar, Slyle
P/aceHo/der. .
toolbar, ,
Customize oolbar, ' ,
buttons toolbar. AllowCustomize
.
button
toolbar, 10

oolTipText . button toolbar,
ButtonClick. Button,
. Key, control.

--
o ol b r . vb p, -

1 88 - - - - - -- - - - -- - --
RichTextBox control toolbar
WordPad.

'1
'''''' 1[iO -1"1l"i"E] !R..
cJs;loriZ'e 1oc1Ja 1 ReloeTooI>r

Gai a ::i

'{y g G qi q
6
,on
T @rm in o IIermino !
. li n@ l ,' "
- ' jo,: , ,y1r.

~
Hy erte)<l OuvWTO
Mlq umq oq ,,[ I! $ G a Io

fn!WT, ..n noqqr\nrn

, - .- ., _. ~
. 9.36. .

Cons t Sa veTo olba rKe y = 1


Cons t Sav e To o lba rSubK ey = ~MyT o o l bar
Co n s t SaveT o olbarVal = ~T ru e

Private Sub Form-Load ( )


Dim img X As Listlmage
\ ~ K 6 Ima g e List cont r o l.
Set i mgX = ImageListl.Listlmage s . _
Add ( , ''open" , Lo adPi cture ( " bit rnaps \tlbr_w 9 5 \ open .bmp")) 1
Se t imgX = lmage Li s t l .Listlmage s . _
Add ( , " save " , LoadP ict ure ("bitmap s \tlbr _w95 \save. bmp " 2
Set i mgX = l mageLis tl. Li s tlmag e s . _
Add ( , "'1e f t ", LoadP ict u re ( "'bi t map s \ t 1br_w95 \1 ft . bmp" ) ) 3
Set imgX = ImageListl.Li stlmages. _
Add ( , -" right " , LoadP i ctu re ("'bitmaps \ t 1br _ w95\rt .bmp" ) 4
Se t img X = I mageLi s t l. List l ma ges . _

Add(, " ce nt er" , LoadPic t u r e("bitmaps \t l br_w95 \cnt . bmp" 5


Set i mgX = ImageListl.Listlmage s . _
Add( , "justify " , LoadPicture ("bitmaps \tlbr_w95 \ jst. bmp" \ 6
Se t imgX = I mag e Li s tl.Listlma ges. _
Add ( , "' bo l d " , LoadPicture ("'bitmaps \tlbr_w95 \ bld. bmp" \ 7
Set i mgx = l mag eLis t l . Listlmage s . _

Add( , ... italic" , Loa dP icture ( "' bi tmaps \ t l b r _w95\I t l . bmp") ) 8

I ma geLis t control t oolba r


Toolba r l . I ma ge Lis t = Ima geLis t l

Dim bt nX As Button

--
\ butt ons

1 89
\ Add .

Se t btnX To o l b a r l . Buttons. Add(, tbrSeparato r)


Set b t n X = Too lbarl.Buttons.Add ( , "open", tbrDefault, ''apen'')
b tnX. To o 1 Ti p Text ~Open Fi 1e "
b t n X. De s c r i p t i on btnX.ToolTipText
Set btnX = Toolbarl. Buttons. Add ( , " save " , tbrDefault , "save")
b t nX. To o l Ti p Te x t = ~Save F i1 e"
btnX.Descri p t ion = btnX.Too1TipTex t
Se t btnX Toolbarl. Buttons . Add ( , tbrSeparator)
Se t btnX = Too lbarl .Bu ttons .Add( , ~ 1e f t ", tbrButtonGroup, ~left")

b t nX. To o 1 Ti p Text "Align Left"

btnX.Desc ription btnX.ToolTipText


Se t bt nX = To o l b a r l . Buttons. Add(, "center " , t brButtonGroup, "center" )
btnX.ToolTipText = ~C ent e r"

btnX.Description = btnX.ToolTipT ext


Set btnX = To o l bar l . Buttons. Ad d (, "right", tbrButtonGroup, "right " )
btnX.ToolTipText = "A1 i g n Right "
btnX.Description = btnX.Too1TipTe x t
Set b tnx Too lbarl. Buttons. Add( , tbrSeparato r )
Set b tnX = Toolbarl .Buttons.Ad d ( , ~bold ", tbrCheck , "bo1d")
btnX.Too1TipText = "Bold"
btnX.Descr ipt ion = b t n X. Too lT ipTe xt
Set btnX = To o l b a r l . Buttons. Add ( , "ita1ic" , tbrCheck, "italic" )
btnX. Tool TipTex t = "It al i c"
btnX.De scr ipt ion = btnX. ToolTipText
Se t btnX = Toolbar l.Buttons.Add ( , tbrSeparator )

\ button l P laceho lder s t y 1 e . ~ ComboBox control


\ b utton.
Set btnX = Too lbarl . Buttons. Add ( , " c ombol " , tbrP1aceholder )
btnX.W idth = 2000
Show

ComboBox control l l l

. but ton.
With Combol
.Width Toolbar l . Buttons("combol" ) . Width
. = To olba rl .Buttons("combol").Top
. Le f t = Toolbarl.Buttons ("combol") .Left
Addltem ''B lac k''
Addltem ''Blue''
Ad d l t e m "Red"
List Index =

End With

With Toolbarl
.Wrappab1e = True
. Al l owCu s t omi z e = Fa1se

-
.-
19 0
En d With

with CommonDialogl
. Defau ltExt = ~ . rtf"
. Fi l t e r = "RTF fi le ( *. RTF) I *. RTF "
End With

With Commandl
. Left = Toolbar 1.Buttons(2 ).Left
. = Toolbarl.Top + To olb a rl .He i g h t + 100
Width = 15 0 0
Height = 300
. Ca p t i o n = " Cu s t omi ze Toolba r"
End With

With Cornmand2
. Left = Cornmand1.Left + Cornmandl.width + 50
. = Cornmand 1.Top
Width = 1500
Height = 300
.Caption = "Restore Too lbar"
En d With

, margin ll RichTextBox
, lQl control.
r ich t ext b ox l. Ri g h t Ma rgin = r ichtextbo xl.width
End Sub

Privat e Sub Forffi-Re s ize( )


wi t h Cornbol
. wi d th = Too lbar l .Buttons ( "cornbol" ).Width
. = Toolbarl. Buttons("combo1 ").

. Left = Toolbar1. Buttons("combo1"). Left


End With
End Sub

Private Sub r icht e xtbo x1 -SelChange( )


a lv RichTextbox control
l l ln Too lbar.
l l Se lAl ignment ll , 1, 2, Null .

Se lect Case r ichtextbo x1 . SelAlignment


Case 1s = rtfLeft '

Toolbar1.Buttons (~left" ) .Value = tbrPre s s ed


Case 1s = r t f Ri g h t

T o o l ba r l . B u t t o n s ( ~ r i ght " ). Val u e = tbrPressed


Case 1s = r t f Ce n t e r '2
Toolbarl.Buttons(~center") . Va lue tbrPressed
Ca se El s e ' Nul l
Too lbarl. Buttons(" left"). Value = tbrUnpressed

--
To o l b a r l . Bu t t on s ( " r i g h t " ). Va l u e = tbrUnpressed

19 1
Toolbarl .Buttons( ~center" ) . Value tbrUnpressed
En d Select

Se1Bo1d ~~ , -1, Null


~ Nu11 MixedState x~ ~ True
Select Case richtextbox1.SelBo1d
Case \ Not bo ld.
Toolbarl.Buttons(~bold")
.Value t brUnpressed
Case -1 \ Bold.
Toolbar1.Buttons(~bold" ).Value tbrP ressed
Case Else \ Mixed state.
Toolbar1.Buttons(~bold").Mixe
dState True
End Select

Sel1talic ~~ , - 1, Null. ~

Mi xedState ~ ~ x~ ~ True.
Select Case richtextboxl.Sel1talic
Case \ Not italic.
Toolbar1.Buttons(~ i talic").Value tbrUnpressed
Case - 1 \ 1talic.
Toolbar1.Buttons(~italic"
) .Value tbrPressed
Case Else \ Mixed State.
Toolbarl.Buttons( ~italic" ).MixedState True

End Select
End Sub

Private Sub Toolba r1-ButtonClick(ByVal Button As Button)


~~ Key Button ,

o~o toolbar .

Select Case Button.Key


Case Is = Uop e n" \ Open file.
Dim strOpen As String
CommonDialog1. ShoWOpen
strOpen = CommonDialogl. filename
richtextboxl.LoadFile strOpen,

Case Is = Us a v e" , Save file.


Dim strNewFile As String
CommonD ialogl. ShowSave
strNewFile = CommonDialog1. filename
richtextboxl.SaveFile strNewFi le ,

Case Is = ul eft"
richtextbox1. SelA1ignment rtfLeft
Case I s = ucenter"
richtextbox1 . Se lAlignment rtfCenter
Case Is = Uright"

--
richtextbox l. Se lAlignment r tfRight

1 92
Case I s = "bold"
If Button.MixedState True Then
But ton.MixedState Fa lse
End If
richtextbo xl . SelBold Abs(richtextboxl.SelBold) - 1

Case I s = "italic"
If Button.MixedState True Then
Button.MixedState False
End If
richtextboxl . SelItalic Abs (richtextboxl.Sel Italic) - 1
End Select
End Sub

Private Sub Combol-Click()


With richtextboxl
Select Case Combol.ListIndex
Case

Se l Colo r vbBlack
Case 1
SelCo lor vbBlue
Case 2
.SelColor vbRed
End Select
End With
richtextboxl.S etFocus
End Sub

Private Sub Comrnandl_Click ()


With Toolbarl
SaveToolbar SaveT oolbarKey, SaveToolbarSubKey, SaveToolbarVal
AllowCu stomize True
Customi ze
AllowCustomiz e False
End With
End Sub

Private Sub Comrnand2_Click()


Toolbarl.RestoreToolbar SaveToolbarKey,
SaveToolbarSubKey, SaveToolbarVal
End Sub

TreeView
TreeView control n ,
File Manager. item - Node ( )
+ -, items,

--
(expanded) (collapsed) .

1 93
8 b oot


! '._. ! F' sISibling
:'0 Nc
i_ "' !! lasSiblirg
. b Parent
8 b U sQrIed
:- -[!) lsa
iII ot:) GeQ/f
gob SQfted
~Beth
:--- !! Drew
8 b S QfIedD escen&1ts
8 - f2: Ann
; '. !! Dave
[ ... [!) Sid
8 - b Pam
j- ffi) BiII
, !! GIenn

. 9.37. TreeVew conIrol .

TreeView control,
:

! Node root .

Child Node child .

Parent Node parent .

Next Node .

Previous Node .

, bitmaps ,
TreeView control ' ImageList control. Style
control, ..
, '
TreeView control , Add. ,
, control.
Dim nodX As Node
Set nodX TreeView1.Nodes .Add( " "R", "Root" )
Set nodX T reeViewl.Nodes.Add ( ~R" , tvwChild, "Cl" , "Child 1 ")
Set nodX TreeViewl. Nodes.Add(~R", tvwChild, "C2","Child 2")
Set nodX T reeViewl.Nodes.Add (~R" , t vwCh i ld, "C3" , "Child 3" )
Set nodX TreeViewl.Nodes.Add(~R", tvwChild, "C4", "Child 4")
nodX.EnsureVisible
TreeViewl.Sty le = tvwTree l i nesText ' Style 4.
TreeViewl .BorderStyl e = vbFixedS ing le
End Sub

Private Sub Form-Click ( )


Dim i As Integer
Dim strNodes As String

--
1 94
For i = 1 TreeVi ew l .Nodes. Count
strNodes = s trNodes & TreeView l .Nodes(i) . Ind e x & U &_
UKey: U & Treev iewl . No des ( i) . Key & U " & _

UText : " & TreeViewl. No de s ( i ). Te x t & Chr(1 0)


Next i
MsgBox s t rNodes
En d Sub

TabStrip
TabStrip controi SSTab Dialog control
,
, .

......

. 9.38. abStrip conIro.

Animation
Animation control (silentAudioVideo lnterleaved)
(frames), . "
" folders, Windows 95. .AVI
\Graphics\AVI CD-ROM Visual Basic.

CURRENT.DOC
FIom 'JOBS'1o 'M yDOC1ATI!!I1!~'
. .l.I . ~ . ~ - II..9ri#UI

. 9.39. Animation control .

Animation control
. .AVI ,
Multimedia (MCI) control.
Dpen control, .AVI, Play
, , , Stop . , video
Close. .
, Animation control anmAVI,
CommandButton controls cmdPlay cmdStop CommonDialog control
dlgDpen:
Privat e Sub cmdPla y_ Click( )
l l ComrnonD ia l og c o nt r ol VlQ l

--
\ . av i VlQ l .

- - - - - - -- - - - - -- 195 - - - - - - -- - - - - - -
d l g Open. Filte r = ~A I ( *. avi) j *.avi n
d lgOpe n . ShowOpen
a nmAv i . Ope n d lgOpen.F ileN ame
a nmAVI . Pla y
End Sub

video:
Private S ub cmdS top_Click ( )
arunAVI . Stop
En d Sub

Play
(repeat, start stop) ,
, frame m.
repeat, .AVI .
1 , frame (
frame ) :

arunAVI. P l a y 1 0, 5, 15

Muftimedia
Multimedia control Media Controllntertace (MCI), ,
sequencers, CO-ROM drives, audio players, videodisc pIayers, videotape recorders players. control
, m MCI
compact disc player.
,
, Next, Play, Pause, Back, Step, Stop, Record Eject.

. 9.40. Multimedia controI.

Multimedia control.

animation Ani maton.

cdaudio CD player .
daI player
sequencer .mid D sequencer.
C Vd e ota pe recorder player.
video . ai video.
videodisc Videodisc player.
waveaudio .wav WavefOl . n J p .

Command control
MCI Win32 , Play, MCI,
CL.
,

--
Command control m C.

196 - - - -- - - -- - - -- - - -
MCI

Open MCI MCI.


Close M C COS E MCI.
Play MCI MCI.
Pause MCI C RESUME .

Stap CS MCI.
Back MCI STEP tracks.
Step MCI STEP tracks.
Prev MCI SEEK track Seek.
Seek MCI SEEK track.
Record CRCRD MCI.
EjecI MCI SET CD-RDM.
Save MCI SAVE .

, Multimedia control
:

n 1 6n Not i fy Tr u e , Done
n - MCI.
MMControll .Not ify = False
\ 1 6 n Wait n

0 n MCI .
MMControll. Wa it = Tru e
\ n Sh a r e a b le 0 MCI


, .

MMCont roll. Share abl e = Fals e


\ De viceType ~ ~ K o ~ MCI .
MMContro ll .De v i c e Type = "CDAud io H
, MC I .
N
MMCont r ol l . Command = Open

, ,
, :

Pr ivate Sub For.m-Unload ( Ca nc el a s Inte g e r)


MMControl l .Command = Clo s e"
En d Sub

Microsoft FlexGrid
control Visual Basic 5.0 FlexGrid

. Grid control, ,
, ,
( ) . , bound control,
MS Access ( ) .
FlexGrid, , ,

--
.

1 97
, (cell) Fl eG rid control
. Row Col , '
Text.
' , WordWrap True,
.
ColWidth RowHeght ,
. controI Cols
Rows.
FixedCols FixedRow,
(default 1 ) FleG ri d control.

(scrolling) control .
CellAlignment '
, ColAlignment , FixedAlignment
.
FleGrid
control
, CellFontName, CellFontSize, CellFontBold, CellFontltalic, CellFontStrikeThrough,
CellFontUnderline CelJFontWidth, CellBackColor CellForeCoJor
. CellBackColor
. ' BackColorFi ed . , ,
BackColorBkg BackCoIorSel .

.. Fo m1 I!!lIiIEJ
Produt!
1. Wahoos
1. W ahoos
3. Foobars
4. Applets
I ~ An nIPI"l._<:'> I'If?/1

. 9.41. " " control.

' . Grid.Vbp
ReG ri d control Load
:

P r ivate Sub Form-Load()


Dim , j

, 06 . . 1. .

MSF lexGridl. Cols 4


MSFlexGridl.Rows = 61

, . . .
, FlexGrid c ontrol.
MSF l exGridl.BackColorBkg = vbGr een
MSFlexGridl.BackColorFixed = vbCy an
MSFle xGr i d l. Bac kColo r Se l = vbBlue

- - - - - - - - - -- - - - -
--
1 9 8 - -- - - - - - - - -- - - -
\ O ~ 6 V1Q headers ( 1 K a ) .

\ ~ .
MSFlex Gr idl.Row

MS FlexGrid l. Col 1: MSFlexGrid l.Text " 1"


MSFle xGr idl .Col 2: MSFlexGridl. Tex t " 2"
MSFlexGr idl . Col 3: MSFlexGridl.Text " 3"

o x~ .
\ help 0 .

MSFlexGridl .CoLAl i gnment (3 ) = 7


\ bo l d headers
.
Fo r i = 1 3
MSFl exGr i d l. Col = i :
MS FlexGr idl . Ce l l BackColor = QBCo!or (Rnd * 15)
MSF lexGrid l.CellFontBold = 1
Next
\ O~6 .
\ 1 0 0 4 .
MSFlexGridl.Col =
Fo r i = 1 60
MSFlexGridl. Co lWidth( O) = Te xtWidt h (" a" ) * 5
MSFl exGridl.Row = i : MSFlexGrid l .CellFontBold 1
MSFl e xGr i d l . Text = CStr(i)
Next
\ FlexGrid cont r ol .
MSFlexGridl.CellFontBold =
For i = 1 3
For j = 1 60
MSFlexGrid l.Row = j: MSF lexGri dl. Col = i
MSFlexGridl .Text = "Text " + CStr ( i ) + CSt r ( j )
Next
Next
( 0, 0) .
MSFlexGridl.Row =
MSFlexGridl. Col =
MSFlexGridl.RowHeight( O) = TextWidth( "a") * 5
MSFlexGr idl . Cel lPictureAlignment = fl e xAlignRi ghtCe nte r
Set MSFlexGridl.Cel lPicture = !mage l .Pi ct ure
End Sub

.
' mj :

Pri vate Sub MSFle xGr i d l-Db lC lick ( )


MsgBox MSFlexG rid l . Te x t
End Sub

--
1 99 - - - - - - - - - - - - - - -
:

... FOfml I!!!lliIl3


~ al
1 exll
2 ex1 2
"'''
"'32
3 e;..1 3
e14
"'''
t34
5 Text15 "'35

7
"''''
l37
8 ;l:l
9 et1 9
"'''' "''''
1(>)(13:9
""'"
10 Te;\l;110 m21 0 e::ll:310
11 e::\I:ll 1 ",'" t3H
12 Text112 ~21 2 W312
13 et11 3 T e.21 3 10.'4313
,. ex114 Text21 4
15 m115 ~ 5

. 9.42. FlexGrid "rol .

FlexGrid control ,
.
Sorl,
MergeCells. , ,
MergeCells
MergeRowO MergeColO True .
, MergeCells.

IlexMergeNever (DefaU t) .

tlexMergeFree 1 .

flexMergeRestr ictRows 2 .

tlexMergeResfrictColumns 3 .

flexMergeRest rictBoth 4 .

, .
, ,
' .
Merge.Vbp FlexGrid control
. , , FormalSlring,
, ,
.
( : ). '
! <, , > ,
' , .
TextArray, :
obj e ct.Text Array (cellinde x ) [= s t r i ng ]

--
cellindex -

2 00 - -- - -- - - - - - - - - -
Cols .
cellindex :

Func t i on falndex(row As I nteger . c ol As Int eger) As Long


f a lnde x = row * MSFlexGri d l . Cols + co l
End Func t i on

MouseRow MouseCol,
. , ColPosition
twips control
.
,
. (dragging) :

\ Fl exGri d control
Pr i v a t e Sub Form-Load{)
Dim As I nt eger

Fgl. Cols = .4
Fg l .Rows = 20
Fgl . Me r geCe l l s = 2
Fg l .F i x edCo l s =

Fgl.FormatStri ng = "< OEplOXn 1< 1< > "

For = 1 Fg l . RowS - 1
, .

Fgl. Te xtAr ray(Fgi( I , ) } RandomStr i ng( Q)


\ .

Fgl . Te xtArray(Fg i (I , 1) Rand omString( 1)


\ .
Fg l.Te x t Ar r ay (Fg i ( I , 2 Rando mStr i ng ( 2}
Fgl .TextA r r ay(Fgi( I , 3 Fo rmat( Rnd * 10000, "'1.00 " )
Ne xt

, . inn.

Fg l . MergeCol(O ) True
Fgl . Me r g e Co l (l) True
Fgl .MergeCol(2) True

, T ~ .

DoSort
End Sub
, X~ o o ~ ~ TextArray ~~.

Funct i on Fg i ( r As Inte g e r . c As I nt eger) As Int e g er


Fg i = c + Fgl . Cols r
End Fun c tio n
, ~ .

Sub DoS ort ( )


Fgl. Col ~

--
Fgl . Co l Sel = Fgl. Co l s - 1

2 01
Fg1. Sort 1
End Sub

\ o ~ y ~ FlexGr id .
Func tion Ra nd omString( kind As I nte ge r)
Dim s As St ring
Se lec t Ca se k i nd
Ca se \ Reg i on.
Select Cas e (Rnd * 1000 ) Mo d 5
Case : 5 - ~ 1 . "
Case 1: s = ~2 . ~~"
Case 2: s ~3 . "

Ca s e 3: s = "4. ;"
Cas e El se: s = "5. "
End Select
Cas e 1 \ Pr o d uc t .
Sele c t Case ( Rnd * 10 0 0) Mod 5
Ca s e : s = "1. Domi n u s "
Ca s e 1: s = " 2. Ta ngr am"
Ca s e 2: s = ~ 3 . VB 5 . "
Case Else: s = ~ 4 . TgReport"
End Se l ect
Cas e 2 \ Employee.
Select Ca se (Rnd * 1 000 ) Mod 4
Case : s " "

Case 1: s = ~ N Ko"
Case 2: s = ~"
Case El se: s = ""
End Select
End Sele ct
Rand omString = 5
End Function

l ~ Tag ~~6 yl Q K ~ ~ 6

l ~o ~ l.

Private Su b Fg l-MouseDown(Button As I n t ege r , Shi f t As I n t e ger, As S ingle,


As Single)

Fg1.Tag = \\"
If Fgl.MouseRow <> Then Ex it Sub
Fgl. Ta g = St r ( Fgl. MouseCo l )
Mo u seP oin t e r = vbS i zeWE
End Sub

\ o ~ oo~ ~ . l

Pr i v a te Sub Fg l-Mou s e Up ( Button As Inte ger, Sh ift As Int e ger, As Si ng l e ,

As Single )
Mo u sePoin te r = vbDe fault
I f Fg l . Tag ~ " Th e n Exit Sub

--
Fg l. Redraw = Fal s e

2 02
Fgl . ColPosition( Val( Fgl. Tag Fg l .Mo useCol
Do So r t
Fg l .Redraw = True
End Sub

Pr iva t e Sub Fg l -DblC l ick()


MsgBox Fg l .Text
End Sub

"'"
l,Avo le~o J-t
C!'o
4, 1 gRe/1 N,;Q
2. am (;n

~ kPC'~ 4, 1" !jRe/t

I(.;,o ~o"
1. O<Wine t:::.~

1. .: -~
fb>Ji\Q<;
4, 1 e , t:::~o"

2.1"4f\9laII1 ~~a-",

. 9.43. FlexGrid control.


FlexGrid control,
Addltem, :

ob jec t . AddItem (item As String [, index ] )

item ,
index .
, tab (vbTab) .
Removeltem Clear
FlexGrid control. :

Dim i

MS Fl e x Grid l .Col s = 2 .

For i = 1 100
MSFlexGrid1.AddI t em ~E ntry ~ & v bTab & i .

Next
Fo r i = 1 50
MSFlexGridl .RemoveItem i . .

Next
MSFlexGridl .C lear K ~ c ont r ol.

ColSel RowSel
.
.
Spread.vbp , FlexGrid textbox
control spreadsheet .
, CellHeight, CellWidth,
CellLeft CellTop, twips.

- - - - - -- - -- -- - - -

-
.-
203 - -- - - - - - - - - - - --
M.,j

,,
1

5
'33' noo ,;..j

,,
7

~~
12
__~~~-t~=~---=~::=-
~_ _ ---+------ +---- I-- _~_~ ~ .

"" -~+-

"
16

. 9.44. FlexGrid conlrol, .

u FlexGrid control Fg2 ' tetbox


control ttEdit Visible BorderStyle u False
. u u u :

Private Sub Form-Load{)


Dim i As I nteger

, .

Fg2.ColWidth (O ) = Fg2.ColWidth(O) 2
Fg2.Co lAl ignment(O) = 1

, nl. labels YlQ . .

Fo r i = Fg2.FixedRows Fg2 .Rows - 1


Fg2.TextAr ray (Fgi(i , = i

Ne x t
For i = Fg2 .FixedCol s Fg2.Cols - 1
Fg2 . TextAr ray(Fgi(O , i ) ) = Chr$(Asc(''A" ) ~ 1 + i )
Next

txtEdit
End Sub

\ l l space ( )
Private Sub Fg2-DblClick ( )
MSFlexGridEdit Fg2 , t xtEdit, 32
End Sub

\ . textbox control.
Private Sub Fg2-GotFocus ( )
If txtEdit . Visible = False Then Ex it Sub
Fg2 = txtEdit
t xtEdit .Visible = False
End Sub

, . t e xtb o x c o nt r ol.
Private Sub Fg2-eress(escii

--
As I n t e g e r )

2 04
MSFlexGridEdit Fg2 , txtEdit, KeyAscii
En d Sub

P riv a t e Sub Fg 2-Leave Ce l l()


If t xtEd it. Visible = Fa l s e Then Ex i t Su b
Fg 2 = t xtEdit
t x tEdit.Vis ible = False
End Sub

\ X ~ oo~1 TextArray ~~
Funct i on Fgi(r As Integer, c As I nt e g e r) As Integer
Fgi = c + Fg2.Cols * r
End Fu nct ion

, 1 textbox control 1
Sub MSFlexGridEdit (MSFlexGrid As Control, Edt As Control, KeyAscii As I n t e g e r)
\ .
Selec t Case KeyAscii
\ ~ text.
Case 32
Ed t.Te xt = MSFl exGrld
Edt . Se l St art = 10 0 0
r 1Q 1 V 1 K text.
Case El s e
Edt = Chr(KeyAs cii)
Edt.SelStart = 1
End Select
\ t e xtbox control .
Ed t.Move MSFlex Gr i d.Cel lLe f t + 120 , MSFlexGr i d . CellTop + 120 ,
MSFle x Gr id. Ce l l Widt h , MSF l exGr i d . Cel l He i g h t
Ed t . Vi sible = Tr u e
\ 1 .
Ed t. Set Fo c u s
End Sub

P riv a t e Sub txtEdit-e yDown( Key C o de As Integer, Sh ift As Integer)


EditKeyCode Fg 2, t xtE d i t , KeyCod e . Sh ift
En d Sub

, 1 beep Ente r .
Privat e Sub t xtEdit-eyPres s(KeyAscii As Integer)
If KeyAscii = 13 Then KeyAscii =
End Sub

\ 1 o~ ESC ..
Su b Edit Ke y Code ( MSFlexGr i d As Contro l , Ed t As Contro l , Key Co d e As Intege r ,
Sh ift As Int e g e r )
Select Case KeyC o de
Ca s e 27 ' ESC: text K~ 10 MSFlexGr id
Edt. Visible = False

--
MSFlexGrid. Se t Fo cus

2 05
Case 13 ' ENTER av l ~o ~o MSFlexGrid.
MSFl exGrid. SetFocus
Cas e 38 ' .
MSF l e xGrid. SetFocus
DoEvents
If MSFlexGrid.Row > MS FlexGrid. FixedRows Then
MSFlexGrid.Row = MSFlexGrid.Row - 1
End If
Case 4 ' ,

MSFlexGrid. SetFocus
DoEvents
If MSFlexGrid.Row < MSFlexGrid.Rows - 1 Then
MSF1e xGr id.Row = MSFlexGrid.Row + 1
End If
End Se le c t
End Sub

(scrolling) bitmap
Scrollp.vbp ,
, (scrolling) bitmap
; .

. 9.45. , BiImap conIrol'

Scrollp.Frm:

--
206
event Resize Ka~ 6~ ~6~.

10 ~ 1 s cro l l ba r s

picture control.
1 1 scrollbars

Pr i v ate Sub FoDn-Resize( )

VScro l11 .Move Sca leWidth - VScro l 11 . Wi dt h, , VScrol11.Wi dth,


Sca l e Height - HS crolll.Height
HS crol11. Mov e , Sc a l e Height - HSc rolll.Height , Sca leWidth -
VScrolll.width
Pi ct ur e l . Move , , VScro lll.Left , HScroll l . Top

VScrolll.Va lue = 'n~o VScro l l l _ Change ( ) even t


VD i f f = Pic ture l . Sc al e Heig ht - Pi c ture2 .Height
VSc ro l 11. Enabled = voi f f <=
If VSc rol11 . Enabled Then
VScrolll.Max = Abs (VDi f f )
VScrolll.LargeChange = VScrolll.Max \ 10
End I f
HScrol1 1.Value = ' n ~ o HScrol l l-Change() event
HDiff = Picture1.ScaleWidth - Picture2.Wi dth
HScrol1 1.Enabled = HD if f <=
If HSc ro l 1 1.Enabled Then
HS c ro l ll . Max = Abs( HDi f f)
HScro l11 .Large Change = HScro l1 1. Max \ 10
End If

End Sub
11 Pict ure.Left 1 .

1 picture cont rol 16.

Pr ivat e Sub HScroll l-Change( )


Picture2.Left = - HSc r o l11. Value
End Sub
. Picture .Top 1 n1K

K 1OU picture c ontrol 6.

Pr ivate Sub VScr o lll-Change()


Pictu re2.Top = - VSc rolll . Va l ue
End Sub

(scrolling) list boxes


Lstscrl.Vbp , , timer control,
items Ist bo items
. Lstsc~ .Frm ,
Topl nde list bo item.

--
2 07
_ Q

~:uu: :::~ ::~


Vual' BIIC
4.0 C
: ..: V$ua 8a si::
YiwaI 8asi:: .0
u.s Ba sic 4.0
4.0 ...

Val B..,$ic 4.0 Vn:uaI : 4_0 D


Visual Ba sic 4.0 _ ua ic 4.0 _
al Bac 4.0 F
.. , Sal .c
.. ,
4.0 F

Vis ual BoIc 4.0 al S.sic 4.0


Visual Bas ic 4.0 YisuM S.sic 4.0

~:~: :::~ :: ~ ~ ~I ~:~: :::~ :: ~ ~ r,;-

11 ~xl

. 9.46. list box controls.

Def l nt -

1 list box e s
1 1 1 1 tlmer

Pr l va t e Sub Fo rm-Load ( )
For i = 1 26
lis tl.Addlt em ~Visual Ba s i c 4.0 ~ + Chr $ (i + 64 )
Next i
Fo r i = 1 26
list 2. Add l t e m ~ Vi sual Ba s i c 4. 0 ~ + Ch r$ (i + 64 )
Next i
Ti merl. I nt e r va l = 1
Time r l . En a ble d = Tr ue
End Sub
event timer.

list box.

Prlvate Sub TimerL-Time r ( )


Static Pre vTI-Li s t l

item Listl
TopIndeX-Listl = list l .TopIndex
x ~ a~
I f TopIndeX-List l <> PrevTL-List l Then
item lis t bo x
1 1 0
~ ( scro l l i ng)
K~ ~ l i s t bo x
lis t 2.TopI ndex = TopI ndeX-Listl
PrevTI-Li stl = Top IndeX-Listl
End If
\ ~o ~ o item 1 list bo xe s
If listl. ListIndex <> list 2. Lis t Inde x The n

--
list2.ListIndex list l . ListIndex

2 0_
End If
End Sub

, '

P riva t e Su b Comrnandl-Click ( )
End
En d Su b


Iistbox control checkbox

listbox Visual Basic
checkbox. '
ListView control, Chklst.Vbp.
ListView ImageList control. ImageList
check Listview control. General tab
ImageList control '16 16'.
:

Private I t e mClicked As Listltem


Priva te Sub Form-Load ( )
Dim itmX As ListI tem
Dim i As Integer

' KnO~

'1istview c o n tro l
For i = 1 10
Addltem " Listltem " & i
Next i

' o o o~ o li s t v i e w l i s t b ox con trol


ListVi e wl . View = lw L ist

ListView l.LabelWrap ; False


End Sub

o ~ ~o
'1istvie w c ont r o l u n chec ked
Sub Addltem (itm As St ring )
Di m i t mX As Li s tlt e m
Dim i As Integer

Set itmX = ListVi ew1.Listl tems.Add()

' i c on unchecked
i t mx. Sma lll con =
itmx.Text ; i t m
End Su b

P r l v a t e Sub Li s t Vi e w1_ I t e mCl i c k( By Va l Item As List l tem)


' x ~ IternDblClick ,
' I temCl icked Item
' V ~ x ~o o ~ DblC lick

- - - - - - -- - - - -- --
--
209 - -- -- - -- - - - -- - -
'

Set ItemC licked I tem


End Sub

Privat e Sub Li s t Vi e wl-Db l Cl i c k ( )


' v checked u n checked
'
, ItemClic ked.
With ItemCl icked
If . Sma lll c o n = Then
. Smal l lcon 1
El se
. Smalllcon

En d If
End With
End Sub

11

L!iHem 1
&g,.;mil+
~C l is\lIem3
: lstl Iem 4

Cic l islHem5

t lisl Iem 6
l isllIem 7

to Li~U lem )
lisl l em 9
L.isIIIem10

. 9.47. listview con tro.


Match.Vbp DirWalk, , " "
controls FileListBox File1 DirListBbox 1 ,
, ' .
D , .DLL
C:\Windows ' listbox control:
ReDim sArray (O ) As String

Screen.MousePointer = 11
Call DirWalk ("* . DLL; *. OCX", " : \windows" , sArray)
Screen.MousePointer = 1
For i = UBound (sArray )
List1.Addltem sArray(i)
Next

wildcards
, (;). :

--
2 10
Sub DirWa lk(ByVal sPatte rn As Str i ng , ByVa l Cur r Di r As String,
s Found( ) As St r i ng )
Di m i As Intege r, sCurrPath As String
Dim sFile As St r i ng, i i As I nt e ge r
Dim iFiles As Integer, iLen As Integer
If Right $( CurrDir, 1 ) <> " \" Then
Dir1.Path Cu r r Di r & " \"
Els e
Di r1.Path = CurrDir
End I f
Fo r i = Dir1.ListCount
If Di r 1.Li s t (i ) <> " " Then
DoEvents
Cal l Di rWalk(sPattern, Dir1.List(i) , sF ound(
Els e
I f Right$(Dir1.Path, 1 ) = " \ Then
s CurrPath Left (Dir1.Path, Len( Dir1.Pa th) - 1)
Else
sCur r Path = Dir1.Path
End I f
File l .Path = s CurrPath
Fi lel .Patter = s Pa t t e r n

If Fi l el.ListCount > Then


Fo r ii = File1.ListCount - 1
ReDim Preserve s Found(UBound (sFound) + 1 )
sFou nd ( UBoud ( sFoud ) - 1 ) = s CurrPath & "\ " &

File 1. Li st ( i i )
Next ii
End If
iLen = L eD ir.ath )
Whil e Mid (Dirl . Pa t h, i Le n, 1 ) <> " \"
i Le n = iLen - 1
Loop
Di r l . Pa t h = Mid( Dir1.Pa th, 1, iLen )
End If
Next i
End Sub

--
2 11

1. Iistbox controI .
, , cap-
tion .

2. controIs .
, , , controls
ListView control . ListVew control
control .
contro.

3. FiIeSeIect$,
CommonDialog con-
(DpenShow ) . ,
file system controIs. ' , text box
, IabeI command buttons controIs ( CanceI).

4. . timercontroI,
Line controI .

5. Spread.Vbp, '
button .
MSChalicontrol button,
,
. bar chali.

6.
Windows Explorer. '
controIs. TreeView control ListView conto.
TreeView contro! drives . ' ,
controI , ListView con-
trol icon (
controIs). , Shell.

- - - - - - - - - - -- - - - 2 12
--
~1/
:a..,.....
~

Visual Basic
. . . Clipboard,
. ,
, . . " "
, Windows , DDE OLE,
" " .
.

CIbfl"d

Visual Basic
, Clipboard. ,
, , Clipboard.
SetText GetText,
. SetText Clipboard, , .
:

Clipboard.SetText da ta [ , fo rmat ]

GetText ,
Clipboard , :

des t $ = Cl ipboard.Get Text()

, Clear Clipboard .

controls, text boxes combo boxes controls,
, . ,
Clipboard, cut-and-
paste. , time ,

--
:

- - - - - - - - - -- - - - 213 - - -- - - - - - -- - - -

SelSlart (Iong intege r) .

SelLenglh (Iang inleger) .

SelText .

, text box control:


Textl . SelSt art =

Te xtl . SelLength = Len(Textl.Text)

Te xtl .SelTex t = ~No "

Clipboard,
Copy, Cut Paste.
,
text box (Iocus) , ActiveControl
Screen. , control:

Screen.Act iveCont ro l

.
control text box.
Sub Cop y_Click ( )
Clipboard.Clear
Clipboard.SetText Screen.ActiveControl.SelText
End Sub

Sub Cut_Click ( )
Cl i pb o a r d. Clear
Cl ipboa rd. SetText Sc reen.Act iveControl. Se l Te x t
Screen.Ac t i veControl . SelTex t=""
End Sub

Sub Past e _Click{)


Screen.ActiveControl . SelText Clipboard.GetTe xt()
End Sub

Clipboard , ,
, . ' GetData,
SetData GetFormat, ,
, . SetData Clipboard
. :

Cl ipboard. SetData data , [ format J

data Picture Image picture control, lormat


.

--
214 --------------~
Clipboard form.t
vbCFBi1m.p 2 Bnm.p ( . ). def.u~

vbCFMet.flle 3 .l. ( .WMF)


vbCFDIB 8 Deice-independ ent bi1m.p
vbCFP.lette 9 Calor p.lette

, Clipboard.
Cl i pboa r d. Set Da ta Lo a dPi c t ure ("PAPER. " )

Clipbo a rd. SetData Imagel. Picture

GetData Clipboard. ,
10 Picture Image control:
Irnagel .Picture = Cl i pboard Get Da t a ( )

, GetFanmat
Clipboard. :

Clipboard.GetFormat ( f ormat)

format ; .

Clipbo.r d form.t
vbC FLink &HBFOO ; DDE.
vbC FText 1

vbCFBilm.p 2 Bllm.p (. )

vbCFMeI. file 3 Melaflle (.WMF )


vbCFDIB 8 Device-independent bitmap
vbCFPalette 9 Color palette

GetFormat True, Clipboard


format, FaIse.
, Clipboard:

Sub Form-Clic k ()
Dim ClpFnt , Msg

Error Re sum e Next

If Cl ipboard.GetF ormat (vbCFText) Then ClpFrnt = ClpFmt + 1


! Clipboard.Ge tF ormat (vbCFBitrnap ) Then Cl pFmt = ClpFmt + 2
If Cl i pboard.Get Format (v b CFDIB ) Then ClpFmt = ClpFmt + 4
Sel e c t Case ClpFmt
Ca s e 1
Msg = " Cl ipboa r d ~ x1 "

Case 2, 4, 6
Msg = ~ Clipbo a rd ~ x ~ bitmap. n

--
2 15 - - - - - - - - - - - - - - - -
Case 3. 5. 7
Msg = ~ T O Cl i pbo ar d ~ x~ K~ bitmap. W

Case Else
Msg = ~To Clipbo ar d ~x ~ .

End Select
MsgBox Msg

End Sub

(D D )
Windows. Clipboard
" " " " , ,
. DD , , ,
(background).
.
spreadsheet
Microsoft Ecel.

DDE
, DDE.
destInatIon, source.
Visual Basic 1.0 client sere r.
- destination ( destination) DD ,
.
- source .
19 , ,
- source ( source)
, . , ,
. , ,
, , ,
,
. tems '
.

DDE
DD source ,
. ,
Microsoft.

Program Manager ProgMan


Excel Excel
Word WinWord
Access MSAccess

- - -- - - -- -- -- --
--
216 - -- - - - - - - -- ---
, tapIc .
(document) topIc, Excel, ,
.xLS . XLC Word .OOC . . topic
"System",
.
Items System :

Ilem
5ysltems items Systemtopic, .

opi c s topics / / .

51atus .

Formats Clipboard .

item.
, Excel item (. . RIC1), Word

(bookmark) . control Visual Basic destInatIon , 10 item
Ln kltem , source ,
text boxes, labels pictures i1ems.


(Iink) .
, source destInatIon,
.
Automatic link

source (items) destInatIon, ( hot link
1. ) .
ManuaI Ink
source destInatIon , 10 ( cold link
1.0 ) .
l1y link
source destination ,

destgn
Visual Basic
design time. ,
, . ,
. destination ,
:

(source) .
@! source, Item Edit Menu (
) Copy.
@) VB, control (text , label pIcture)
.

--
Edit Menu Visual Basic, Paste Lnk.

- - - - - -- - - - - - - - - 217
' , control
. automaticlink time .
source ,
design . LinkMode 1-Source.

DDE ruJl trn e



destination ,
cantrals (t box, label p ictre) DDE.
LinkTopic, Linkltem LinkMode, controls .
LinkMode control, DDE,
topic , :

applicat ionltop ic

source topic
" " ( ASCI1124). , spreadsheet Ec el :
EXCEL IC:\EXCEL\SHEETl .XLS

Linkltem control, item . ,


, Excel, item
:

R2C3

, item ,
, LinkMode . 4 , 0-
None, , 1-Automatic, 2-Manual 3 -f.
, Visual Basic .
1-Automatic, (items)
, control Change.
Link_ltem , AutomatIc Excel .
LinkMode vbLinkNone, . control,
, t box label. Excel ,
.

Private Sub Link-It em (Control As Control)


Dim Cur Row As St r i ng
St a ti c Row

Ro w = Ro w + 1
I f Row = 1 Then
Cont rol. LinkMode = vbLinkNone
Cont ro l.LinkTopic = ~ Ex celISheetl"

Con t rol .Linkl tem ~RICl"

Cont ro l . LinkMode = vhLinkAutomat ic


Else
CurRow = ~ R" & Row & UCl"
Cont rol. Li nk l tem = CurRow
End I f

--
End Sub

- - - - - - - - -- - - -- - 2 1 8 - - -- - - - - - - - - - - -
LinkMode 2-Manual, , control
. ,
, LinkRequest.
, control
LinkRequest, spreadsheet Excel:
Priate Sub Lin k-I tem ( Con t r o! As Cont r ol )
If Contro l . LinkMode = vbLinkNo ne Then
Cont ro l . Li n kTopic = "Exce l ISheet l"
Control .L inkltem = "RI C1" ' It e m
Cont rol.L i nkMode = vbLinkManu a l
Cont rol. LinkReques t , c ont r o!
Els e
! Contro ! .Linkltem "RICl" The n
Contro l .Linkltem "R2 c l "
Cont rol. LinkRe qu est c o nt r o !
Else
Contro! .Linkltem = "RIC l"
Cont r o l . Lin kRe q ue s t , c ont r o l
End I f
End I f

End Sub

, !
, ,
Shell.
S ub St a r tapp ( Control As Co n tro l, App Name $ , To p i c $ , Mode % )
Const DDE-NO-APP = 283

Error Go To Sta rtUp


Contro l . LinkMode = vbLinkNone
Control.LinkTopic = AppName & " " & Topic
Cont rol. LinkMode = Mode %
Ex i t Sub

S tartUp:
I f Er r = D D -- Then
i = Shell(AppNarne)
Re surne
El s e
Ms gBox Erro r $
End
End If
En d Sub

[ LinkMode 3- , 2-
Manual,

--
LinkNotify. ,

- -- - - - - - - - - - - - - 219 ~ - - - --- - - -- - --~


linkRequest. , bitmaps.
, c linkMode
3- LinkNotify,
. linkRequest, bitmap
.

Pr i vat e Sub Pi c t ure L-Li nkNot i f y ()


If Scre en.ActiveForm 15 Me Then
Pict ure l . Li nkRe que s t
End If
End Sub

, DD , source desti-
nation. LinkPoke, destination
source, . :
Textl . Li nkMode =
W
Te xtl .Li nkTopic = - Exce l l Sheet l
W
Textl .Link l tem = -R2C3
Text l . Li nkMode = 2
Text l. Text = ~New alue w

Textl .LinkPoke
Textl. LinkMode =

DDE,
linkExecute. , . ,
, worksheet Excei.
Te xt l . Li nkExe c ut e ~[FI LE.C LO S E ( ) ] "

.
DD Excel, worksheet
:

Pr i v ate Sub Form-Cl i c k ()


Dirn Cmd. . Q. Row,
Q = Chr(34) \ 1 0 lv

nl0y Exce l
cmd C V ' & Q &"SHEETl" & Q & 'j]"

cmd = Cmd & '[SELECT t' & Q & ' Rl Cl : R5C2 " & Q & 'j ]"
Cmd = cmd & '[NEWt2 , ) ] [ARRANGE. ALL t) J "

! Text l. Li n kMo de = v bLin kNone Then


= She l l ( ' c e " , 4) ' l. Exce l .
Te x t l . LinkTo p ic = ~E xc el l S he e tlH , l t op i c .

Te x t l . Li nk ltem "R1Cl " \ l it em .


Te x t l . Li n kMode = vbLinkMa nual ' l mode .

End I f

lQ LinkPo ke ,

--
Fo r = 1 5

2 20 - - - - - - - - - - - -- - - -
Row =:
Text l .Linkltem =: ~Rn & Row & ~C l n

Te xtl.Text = Chr(64 + )
Te xtl.LinkPo ke
Te xtl .Link l tem =: ~ R " & Ro w & C2 "
Textl .Text = Row
Te xtl. LinkPo ke
Next

Te x t l . Li n kExe c ut e Cmd \ Excel .


End Sub

, destination, source .
, . LinkTopic
topic,
application (
project, Visual Basic).
Items controls (text boxes, lables bitmaps). ,
, source , LinkMode
1-Source.
DDE, LinkNotify.
, :

linkOpen destination source.


,
m .

linkClose destination source. -


destImatIon ,
source destination
.

Li n k r , DDE.
LinkExecute s o U ce , destination
.

linkNolify destination. source item


.

ArJAY
,
Visual Basic Copy Paste Link Edit menu.
.
Paste Link, destination
Clipboard .
, GetText Clipboard
( ) , vbCFLink(&HBFOO).
, :

Link$ = Cl ipboard.GetText(vbCFLink)

--
Link$ :

- - - - - - - - - -- - - - - - 221
applicationltopic !item

topic item 124.


Clipboard, DDE,
:

I f Clipboard.GetFormat(vbCFLink) Then
\ M~ DD
Ed If

,
' menu Paste Link mnuEPaste.
, ,
control , :

Private Sub mnuEPaste-Click ()


Dim item As Integer, Link As String

Link = Clipboard.GetText (vbCFLink)


item = InStr(Link . " !")
If item <> Then
Screen.ActiveControl.LinkMode = vbLinkNone
Sc reen.ActiveControl.LikTopic= Left$(Link, item - 1)
Sc reen.ActiveCotrol.Linkltem Mid$(Link, item + 1)
Scree n .ActiveControl.Li nkMode = vbLinkAutomatic
Elself InStr (Link. "") Then

M~K D ~ items

Sc r e en.ActiveControl.LinkMode = vbLinkNone
Screen.ActiveContro l. LinkTopic = Link
Scre en.ActiveContro l . Li n k l t e m
Screen.ActiveControl.LinkMode = vbLinkAutomatic
End 1f
End Sub

Clipboard
. ,
Click
mnuEdit menubar. Clipboard
mnuEPaste.

Private Sub mnuEdit-Cl ick ()


mnuEPaste.Enabled = False
1f Clipboard.GetFormat (vbCFLink ) Then
1f TypeOf Screen.ActiveControl 18 PictureBox Then
1f Clipboard.GetFormat(vbCFBitmap) Then
mnuEPaste.Enabled = True
End 1!
Else1f TypeOf Sc reen.ActiveControl 18 TextBox Then
1f Clipboard.GetFormat (vbCFText ) Then
mnuEPaste.Enabled = True
End 1f
End 1 f
End 1f

--
End Sub

222
Copy ,
source , Clipboard,
:

appl icationltopic !item

application ,
App.EXEName, topic LinkTopic , , item,
Tag control .
mnuECopy :

Pri v a t e Sub muECopy_Click ()


Dim AppTopName As 8tring

Clipboard.Clear
If TypeOf Screen.ActiveControl 18 PictureBox Then
AppTopName = App . EXEName & "" & LinkTopic
AppTopName = App TopName & " !" & Sc reen.ActiveContro l .Tag
Cl i pb o a r d . SetText AppTopName, vbCFLink
Cl ipboard. SetText Screen. ActiveCont rol .Pictu re
E!self Ty p eO f Screen.ActiveContro l 18 Te xtBox Then
AppTopName = App.EXEName & " " & Li nkTopi c
AppT opNarne = AppTopName & " ! " & S c reen. Ac t i v e Co nt r Ql . Ta g
Clipboa rd. SetTe xt AppTopName, vbCFLink
Clipboard.Se tText Sc reen.ActiveCont rol.Text
Else
Clipboard.SetText 8creen.Act iveContro l
End If
End Sub

I'ro o r 1'l JJ I 1'l Jl 1'l o er


LinkEecute Program Manager
Windows . , ,
groups items , , ProgramManager. , Windows 95 Program
Manager , .
Program Manager DD destination , LinkExecute,
. , .

CreateGroup group.
DeleleGroup group.
ShowGroup i group.
Reload group.
Addllem item .

Deletellem item.
Replacellem item.
ExitProgman Program Manager.

--
2 23
group item:
[ C r e a t e Gr o up ( ~ Wi ndo w s Appl icat ions")]
[ S h owG r o up ( ~ MY GRO UP .GRP", 1)]
[Add l t e m(wi na pp . e x e , wi n App ,winapp.ex e ,2 ) ]

Program Manager,
'l catn " "Topic" , PRDGMAN. ,
Program Manager, groups items,
CF_. item group,
carriage return
. group ( ) ,
group , items .
' items.
Contrlpm.Vbp
Program Manager " " groups items. ,
groups .

... Forml IIi1

!tk:e Ir Qe1ete

~~:,z
.4PfGPlA
J
~:::,,~I?
V'$u41 0 <1$18 .. (1 6-b!]

l4uli,medi<t 0011

MFC S anpJes ( ~
Microsolt
MicrosoIt l C....
QuIc"Pak ProIessio nal 4.0
, l c 4.0
MulIimeda V ie we r 2_0 ::
E"plo, e MultImedia 5 e,i e:
PacilI c ech
Aolloay 6 uId
Int eInet ,gr<mmng

~~:~P~~~32 lic.. t:..=..

.1 .1 . list box groups Program Manager.

Defl nt -

. u~ LOV Program Manager Text l ,


Li n kEx e c ut e , l i t e ms KQl group

Private Sub Commandl _Cl i ck ( )


textl .LinkTopic = ~ProgManIProgman"
t extl.LinkMode = 2
t e xtl .LinkExe cute ~[CreateGroup(Test Group ) ] "

' li i t ems ~o Pr og r am Manager.

t e xtl.LinkEx ecute ~ [ AddItem ( C : \VB4\VB.EXE, Visual Basic )]"


text l . LinkExecute ~[AddItem(WINF ILE .EXE. Fi l e Manager )] "
te xtl ~LinkE xe cu t e ~[Addltem (WORDPAD. EXE , WordPad ] "

--
2 24
t e xt l . Li nkExecute ~[Addlt em (NOTE PAD .EXE setup.t xt . Re a d me ) ] n

\ n~ov group Program Manager.


text l .LinkExecute -[ShowGroup (Test Group, 7)] R
textl.Li nkMode =

\ ~ list box x~

\ gro up s Program Manager.


I f l i st l. Li s t l nde x >= Then
Cal l Command3_Click
End I f
End Sub

~y ~ group Test Group

~ K i t e ms ~ x ~ .

Private Su b Command2-Click()

textl . Li n kTopic = ~ ProgManl P rogmanR


textl . LinkMode = 2
textl . LinkExecute ~(DeleteGroup(Test Group )]n
textl.LinkMode =

\ n1 l i s t box 1

\ g roups Program Manage r.


If list l .List lndex >= Then
Call Cornmand3_Cl ick
End If
End Sub

~ Pro g r am Man ager t e xt l co ntrol K ~

' Li nkR e que s t , 1

groups x~ .

Private Sub Cornmand3_C lick ( )


textl.LinkTopic = P rogMan l Progman n
textl.Linkltem = PROGMANR
t extl.LinkMode = 2
textl. LinkRequest
t extl.LinkMode =

~ li s t bo x group s
Ca l l f l11 1 lstbox
End Sub

? Li n kRe q uest . textl con t ro l . 1


g r o ups Pr ogram Manager
~x ~

CR (1 3) . u x ~ Li s t b o x contro l .

Pr i v a t e Sub fi l l li s t box()

225
--
Text$ = textl.Text
length = Len (Text$)
ReDim x$(length)
listl. Clear

For i = 1 length
dumY$ = Mid$ (Text$, i, 1)
If dumY$ = vbCr Then
i = i + 1
a = a + 1
End If
x$(a) = x$(a) + dumY$

Next i
Fo r i = 1 a
x$(i) ~ Mid$(x$li), 2, Len(x$(i - 1)
l i s t l . Add l t e m x$ (i) -
Next i
listl .Listlndex =

End Sub

textl control , 1 DD 1

Program Manager

Private SubForrn-Load()
textl .Visible = False
End Sub

Jj e!p

Vsual WordPad Read me


Basic

~ objett{s)

. 10.2. group items .

L (Object Linking and Embedding) Windows,


. con-
trol Visual Basic, L
() Windows.
10.3. L control spreadsheet Excel .
L
, . ,

--
spreadsheet ! , -

2 26 ------------~~--
, ..

=
FoImT

D
,

1 Ex"m le 1 - Product mix roblem wIt dimini shil'l roIit m r


- ~ ,.,."...,octve$ 1teIea, Md <pe.okes. ""ing ~ cornmor <1. ffleni:
- powe' ~ . e!<e cone. elc. ,.. .... ew.,,",w~~you "",$ :e~~
- lhe rro;\ po/l:b!e """ 0/ poduct, 10 buId. BJ j>OU(pofil per .rW. buJt dece e. M:h
,
- """", bec.&Joee><l .. ce~;"""'- "'e r..eded lO ld !ned~ ,Nio:n cl1 ~
-
-
.\
,
f'J'f N .M><'
lIJ"""'k> ,>
"...,.." ..." > l ll'<"d
,...,

,
.- "" 1
~

,,,
CIu.<m ."
~
1
1 Pk/tl>!'l' k
"" ~

HJ
!
.,,,,,,,,, ,., Ci:;lt.'I
- .,m-

" ~
,,
2 1

Ektm"....,,
" 600 2 1

. 10.3. Excel.

L control (Iinked objects) ,


(embedded objects), ' .
L control design
time . control ,
(Insert Object dialog)
OLE.

Insert Obje ct 13

B ,lma I mge
Cr cle Oocumenl
r Ceate from EIe:
I nde ~ C"rd
Inlernel Oo.meI ( L
MeofuCip
Miuosoll Excel (l ~ IlyM Ic:on
M CoroH Excel c',,,
.:h
;::;
,, ' _ _..:cJ
:;.

Inrefl $ newAdobeActOOaI Docume nl objed


n yos do.met.

. 10.4. .

'SC " , PropertI es Window,


CIass control ( 10.5. - Ecel EceIWo rkShe et) .
SourceDoc (
c :\ec ei\e am p les\s olve r\s o lv e r4. ls , Ecel) SourceItem
(
R1C1 :R5C6, E ce l ).
DlETypeAllowed
(Iinked, embedded ) , L1 D () , DD D (1) EITHER (2)

--
. , L control

2 27
, '
. DispIayType control
, SizeMode l
.

". , . # l l $ "
joul otE :.:J
-1'"--,1
-.-.
....,
,

.",
,."""""'"
-"

...""'.....
AutoAdivte
,~

:: """"""'"
.."...
, -
r~~~~ - Fed Snje
.=J
t<fi eloj
D<lt4Sc:u, e
sp!yTypoo
Drl,1! CQ(I ....,
,,.""""
0- content

~-
....., "W
'" .:J
"""
'Class
'~sets tIwtdtss lWI'Ie ." efbedded

. 10.5. Properties Window, control.

,
control, menu ( - ) ,
OLE. Insert Objecl.... Insen Object, Delete
Embedded Objecl Objecl.
Paste Special... (Paste Special dialog)
Clipboard . , Clipboard
Copy
, .
( ) time
. , control, ,
Load :

Pr ivate Sub Fo rm.J..oad ( )


OLEl . Cl a s s = ~ E x c e l Wo r k S h e et " Ex cel
OLEl .OLEType Al lowe d = 2
OLEl . So u r c e Doc = ~c: \ e xcel \e xamp l es \s olver \s olve r l .xls"

OLEl . So u r c e I t e m = ~RIC l:R7C 7"

OLE l . Ac t ion =

End Sub

, Paintbrush:
Pr ivate Sub c omma ndl_ Cl i c k ()
OLEl . Cl a s s = "PBr u s h "
OLEl . Sour ce Doc = "c: \ wi ndows\ar c he s . bmp"

Source l tem ~ Pa i nt b r u s h ~l

\ v - ~x l 2 y2 n

.-
22 8

-
OLE1.Sourceltem = ~o 121 159"
OLE1.0LETypeAllowed =

OLE1. Act ion = 1


End Sub

, , Command1 _Click Sound Recorder:


Private Sub Command1~Cl ick ( )
OLE1.Class = ~ SoundRec"
OLEl. SourceDoc = ~c : \win dows \chimes.wav"
OLE1 .Sourceltem = ~Wav e"

OLE1.0LETypeAllowed =

OLE1. Action = 1
End Sub

Action time
, .

embedded.
Class, OleTypeAllawed ( 1 ) Sourceltem.
1 l ked. 01eTypeAllowed ( 2 )
SourceDoc, Sourceltem, .

4 Clipboard, Edit Copy.


5 Cli pboard .
PasteOK rue.

6
L contro).
7 L . Verb,
L .
AutoAclivaIe 2 (Doub!e-Click), L control .

9 .
embedded .

10 . -
.

11
FileNumber. linked,
, .
embedded , control .

12 : SaveToFile.
FileNumber
14 Insert Object.
.

15 Paste Special. -
Clipboard.
17 verbs Verbs -
. , u verbs "edit" "play."
ObjecIVerbs ObjeclVerbsCounI , Verb :::: 1
, Verb :::: 2 .
18 .

--
2 29
OIe.Vbp, , .
,
Copy, Cut, Paste Paste SpeciaI,
verbs . OIe. Frm mod-
uIes. ' , OIe2mod1.Bas .

.. Ob,ect [Wo rdPad Document 1 ] B IiII3


"p' - -'~

VisuaI Basic 4.0

. 10.6. , ' WordPad Ole.

. V C/ipboard .
2. n ;
3.
;

4. n 11em ;
5. ;
6. LinkMode.
7. LinkRequesl LinkPoke;
8. n L ;
9. L conlro/.

destination source
Automatic lnk. textbox controI.
saurce , contraI destinatIan.

--------------~
--
230 - -- - - - - -- - - - - - -


DfJtfJ Cortror

Visual Basic Microsoft Access


. . , BtrIeve, dBase, FoxPro, Paradox OOBC,
. data control, ,
, . , .
Data Crl ,
(DataAccess Objects).
Data Control controls (bound controIs) , text box
. controls
. data control,
,
.


0llt (Tables), (Rows)
(Columns) Excel Lotus 1-2-3.
, (records) (fields)
, ' . 11 .1 .
4 ( ) 6 ( ) .

3 OlIUU:AZIH :l: NIXO:: 8 I'ECIIOHOt:


~ IlMAl!OO OYlOI: Z3~Z"39 . ~Ix::

IE ~~~~~~_~-==;~~--.;;;] t~~!~t
,

--
. 11.1 . .

- - - - -- - - - -- - - - - 231
, , . .
, , .
,
.
,
. ,
.
(primary key)
.
,
.


, ( , ,
) . SQL (Structured Ouery Language)
' . ; (queries)
.
11 .1. SOL
" " " " " " :

"SELECT , FROM

() .

Data C.oJJtrol

data control
Visual Basic, BIBLlO.MDB.

!
. 11.2. data control toolbox .

contro! toolbox, , F. ,
. , '
DalaBaseName '' data control. ,
.
,
RecordSource, (
11 .3.).
t boxes ,
. control, check boxes, pictures
boxes, image controls, labels, DBList, DBCombo DBGrid MSFlexGrid,
(bound contro!s). bound controls data control,
, DataSource, .
data contro!s, '

--
. bound control () . -

- -- - - -- - -- - - - - - 232 - - - - -- - -- - -- - --
DataField,
.

1f t.;. 4- #'.tb

IDat~I " :J
- I~I
..oJ
"""""" ...."".,..

=: .
""",,k~

""
_)

--'0
=:-0

F'"
. C>efd:

0 - No t

'0-.. .
ecordsetType

F~se-
Oynlls!'t

.
RM#To.eft AoA!'S
.,
""",,",
ooIT.pText "."""
'"'
Al Tt~
:!
C-
RecwdSOtJce
}<e.ms(sets the ~ ta:le, SQL

. 11.3. (Table).

text boxes controls,


, ,
11.4. ,- ---,
.. Ttl e s I!!lIiIIEJ

TIIle jSIe pby-sIe p dBjJse


1 58 10-02 00095 -2-5
Ye a I I~995

lBl!J aa1 lIffi

. 11.4. .

, - data control,
, ~, .
text boxes button data control, Visual Basic
. m
, . .

df t. -
data control,
design run time .

Gonnect
,
Microsoft Access.

- - -- - - - - - - -- -
--
233 - - -- - - - - -- ---
DaIabaseName
,
.
ser er ,
.

Exclusive
True,
, .
, , Refresh,
.

Recordset OpIiOnS
, data control ' ,
Recordset, Recordsel.
, :

[ f o rmname. ]datact rl. Re c ordset. prop ertyname [ = pr opert yv a l ue


( f o rmname . ]datactrl .Re c o rdset .methodname [ a rgurnentlist

.
OpIiOnS
.

dbDenyWnle 1 " u u .

dbDenyRead 2 " u u .

dbReadOnly 3 u .

d blpe ndO nIy 8 , .

, ,
"tiUes":
Dat a l .Da t aba s e Name = ~BIBLI O.MDB W

Data l . RecordSource = ~T itle s " t


Datal .Options = dbDeny Read
Dat a l. Refresh

ReadOnIy
,
, ReadOnly True.

Rec:ordSource

data C I' , query

--
Microsoft Access , , SOL query.

- -- - - - - - - -- - - - - - 234
, , SQL
:

Data l .DatabaseName uBIBLIO. MDB "


Datal . Re c ordSou r ce = ~S e l e ct * Fr om Publishers Whe r e s t a te '' "

Data l. Refre sh

; Recordset
' .

RE!c:ordsE!t
' , data
control, Recordset,
SQL query.
Recordset data contro.
.


data control ,
. ' command button
Recordset Addnew, :

da ta l.Re co rdset.AddNew

buttan, baund contrals


data cantraI .
, buttan, Save,
Update.
datal. Reco rds et. Update

.

:
. .
. index ( U) .
. .
. (Iacked).


, Delete.
.
. button
:

datal. Reco rdset. Delete


datal.Re c ordset.MoveNext

MoveNext . data controI

--
, , :

2 35 - -- - - - - - - - -----
[formname. ] datactrl. recordset.MoveFirst
[formname. ]datactrl. recordset.MoveLast
[ f ormname. ]datactr l.recordset.MoveNext
[ f ormname. ]datactr l . recordset.MovePrevious

, , ,
bound controls .
, , BOF EOF,
:

[formname . ] dat ac t r l . records e t.BOF


[fo rmname . ] datactrl . recordset. EOF

( recordset)
, .
, Publishers ' "
. Refresh data control
.

Datal.DatabaseName "BI BLIO. MDB"


Datal .RecordSourc e = ~ S e le ct * Fr om Publishers Where s tate ' '"

Data l.Refre sh

Unti l Da t al. Re cordse t . EOF


Datal . Recordse t . Dele t e
Datal . Recordset. MoveNe xt
Loop

,
' , BoakMark ,
Variant StrIng. ,
, ' :

Dim MyBookMa rk As Var i ant


,

MyBo okMark = Dat al. Recordset. Bookmar k


,

Dat a l. Reco r ds et.Move La st


, X~K

Datal.Rec ordset.Bookmark = MyBookMark

Field
Recordset FieId,
. Field
Recordset Fields. ,
Value ' .
.
. , .

--
" ":

- - - -- - - - - - - - -- - 236
F$ = Dat al. Rec o rdset. Fi e l d s (O).Value '

F$ = Dat a l . Re c o r d s e t .Field !E nwp o '

n=O: F$ = Da t al . Re c ord s e t . Fiel ds (n) '

F$ = D a ta. Rec r dse t . Fi elds ( w " ) '

title $ = " : F$ = Dat a l . Re c ordset. Fiel ds (title$ )

, :

D ata l . Reco rdset. F ie ld s (n E nvOW ) = on W

.
, , "Invalid Use NULL". ,
, "Name" , :

MyName $ = Data .Recr dS e t (ame


W
)

Assign .
Variant " .

Func t ion Ass i gn (Stuff as Variant ) as Var i ant


If I s Null (Stuff ) Then
Assign
El s e
As s ign Stuf f
En d If
End Funct i on

MyName$ = ssign (Dat a . Re c rdS e t ( ame" )

Caunt,
Recordset. list box
:

Fo r i = to Da t a l . Re co r d s e t . Fi e lds. Cou nt - 1
Li s t l .Addl tem Dat al .Recor ds e t .F ie l ds ( i )
Next

,
bound controls:
Dat a l . Dat aba seName nBIBLIO. MDB"
Datal . Reco rdSou rce = nTi t l e s "
Dat a l .Refresh
, n ~oo .

Oata l .AddNe w

, ~ o ~x

Data l . Re cords e t . Fi e l ds ("Title ") ". Vi sua l Ba sic 5. "

Da t a .Re c rds et . Fie l d s



U_
W
) = 37

Oatal .Records et.Fields ( nPuIO" ) 10 0

--
=

2 37
, ~ ~ l ~l .

Datal .Update

, recordset .
Dat a l. Recordset. Close

' ( ) .
:

Datal .DatabaseName "BI BLI O.MDB"


Da t a l. Re c o r d So u rce "Tit les "
Data l . Refresh

Da t al. Recordset. Field s ( "Title ") = " Vis ua l Ba sic 5. 0"

, l

Datal.Up da t e

\ recordset
Dat a l .Re cor d s e t. Clo s e

~ l Vla :

Te xt l . Te xt = " Vi s ual Ba s i c 5. "

1 bound text box control. , bound


control, .

M~oo
.
FindFirst, FindLast, FindNexl FindPrevious, :

[ f o rmname . ] da t a c t r l . r ecords et.FindFir st c rit e r i a


[for.mname . ]dat a ctrl. reco rdse t . Fi ndLast crite r i a
[formname . }datact r l. re c ordset. FindNext c r i t e ria
[formname . ] dat actrl . rec ordset . Fi ndP r e v i ou s c r it e ri a

criteria .
, NoMalch, :

[ fo r~ame. ] datact rl. r eco rds et.NoMat ch

False
.

Dim Criteria As Str ing, Currentreco rd As Va r iant

Datal .Dat abaseName "BIBLIO. MD B"


Data l.Re cordSou rce "Title s"

Cr iter i a = "Ti t l e = 'D atabas e

, 6

Cur r ent reco rd = da ta l . Records e t . Boo kmar k

--
2 38
Datal .Reco r d set .Fi ndFi rst Cr i t eria

Until Da t al . Recordset. NoMatch

B1K~

Datal .Reco rdset.FindNext Criteria


Lo op

~ ~~K ~

datal .Recor dset .Bookmark = Current record

,
Edit, :

[formname .1 datactr!.reco r d set.Edi t

, ' .
,
:

Dim Criteri a As String, NewTitle As St ring

, K1~o

Criteria = ~ T i t le = ' Right Hand'


.
NewTitle = ~My Right Foot"

Datal .Reco rdset.FindFi rst Criteria


Wh i le Not Datal.Recordset .NoMatch
If Not Data l . Re co r cts e t . NoMat ch Then
Dat a l . Recordset. Ed i t
Dat a l .Rec ordset.F ie lds{~Title") Ne wTi tle

, En ~

Data l. Records et. Up da t e


End If
Datal .Re c ordset .F indNext Criter i a
Lo

v dutu coJJtror
data control, DrapDrop, DragOver, MouseDown, MouseDown

MouseUp, , .


data control. :

Privat e Sub d a t a c ont r o l-Error ( Da t aEr r As I nte g er, Response As Int e g e r )

DataErr Response
' , Open,
DatabaseName control:

- - -- - - - - - - - - -
--
239 - - - -- - - - - - - - -
Pri vate Sub Data l-Er r or ( Da t a Erro r As I nt e g e r . Response As Inte g e r )
Select Case Da t a Er ro r
Cas e 3 0 2 4 ' n
CMD i alog l .Action l ' 1 1 0 16 Ope n

End Se l e c t
End Sub

Reposition
. :

Private Sub da tacont r ol. Repo s it ion ()

data control
.
. ,
list box :

Declaratio n s

Dim Loadi ng As lnte g er

Private Sub Form-Load ( )


Dat a l .Da t aba s eName 'C: \ VB\ BI BLIO. MDB"
Dat a l. Re c o r dSou rce = ~ SELECT State FROM Pub l i s he r s"
Loading = Tr ue

1 1 r ecordset.
Data l.Refresh
While Not Datal .Recordset.EOF

I f Not IsNu ll (Dat al .Reco rdset(O Then


lis t box
Listl.Addlte m Da t a l . Re co r dse t (O )
End If

pn

Datal .Rec ardset. Mov eNext


Loop
l ~ n Recor dSo urce.

Datal.Re cor dSource = ~Publishers"


r ecordset an10 i 1

Data l . Re f r e s h
l~ n field text box .

Textl .Dat aF ield = ~ S tate"


Lo a ding = Fa l s e
End Sub

Privat e Sub DataL-Repos i tion ( )


Dim As Integer

If Loa d i ng Then Exit Sub

--
2 40
~ xo list box.

For = Listl.ListCount - 1

I f Listl .List(I) = D at al. Re c o r d s e t ( ~ S t a t e " ) Then


l l list box.
Li s t l.Li s tl nde x =

Exit For
End If
Next
End Sub

Valida\e
, Upda\e (
Upda\eRecord ) , , Dele\e, Unload
Close . :

Sub datacontrol-Validate (Action As Integer. Save As Integer)

Ac\ion ,
.

vbOalaAclionCancel .

vbDataActionMoveFirst 1 MoveFirst.
vbDataActionMovePrevious 2 MovePrevious.
vb O alaAclio nM ove N eX 3 M ove N eX.

vbDataActionMoveLast 4 MoveLast.
vbOalaAclIonAddNew 5 AddNew.
vbOalaAclIonUpdate 6 Updale ( UpdaleRecord).
vbDataActionDelete 7 Oelele.
vbOalaAclIonFInd 8 Find.
vbOataAclIonBookmark 9 Bookmark.
vbDataActionClose 10 Close.
vbDataActionUnload 11 .

Ac\ion,
, . Save
bound conlrols ( True/False) . True,
Edi\ UpdateRecord.
bound controls, bound controls.
DataChanged bound controls , True,
.
, _I
, Text1 control:
Private Sub Datal_Validate (Action As Integer . Save As Integer)
, ~ x o l l

--
I f Textl.DataChanged Th e n

- - - - - - - - - - - - - - - - 2 .. 1
Ms gBox ~ 10 ~."

nn .

Textl .OataChanged ~ Fal se


End 1 f

End Sub

1} dGItGI cOJJt rof


data control , , ,
UpdateConlrols UpdaleRecord,

UpdateControls
bound controls. :

dat actr l.UpdateContro ls

bound controls
, '
,
KeyPreview True:
Private Sub Forffi-eyOown ( Key Code As 1nteger, Shift As Integer)
Const KEY-ESCAPE = &HIB

If KeyCode = E Y---ESCAPE Then


Oatal .UpdateControls
End If
End Sub

UpdateRecord
bound controls .
:

datactrl .UpdateRecord

bound
controls Validate,
. Edit,
Update, .

TrGIJJ sGIctLOJJS
Transaction ' recordset,

. ,
transaction, . transactIon,
.
:
, transaction
,
,

-
.-
242
.
. transaction
, ,
transacfton .
, . Visual Basic
transactIons. BeginTrans, transactIon, GommitTrans,
transaction , , RollBack,
transaction. Transactions,
Transactions recordset True .

Bound ,l5
bound controIs, ' data control
.
controls (Label, TextBox, CheckBox, ComboBox), controls (Image, PictureBox),
(advanced)controls (DBList, DBCombo) , , Bound Grid (DBGrid) MSFlexGrid.
controls data control DataField DataSource. con-
trols DBList DBCombo " " ,
Addltem, ListBox ComboBox
controls. . :

RourceSource
Datacontrol bound
control. run time .

ListField
bound control .
, BoundGolumn .

BoundGoJumn
bound control ,
control. ,
BoundTex1

BoundText
BoundColumn.

MatchEntry
bound control.

RourceSource design
. . m

DBList OBCombo ;
data control. ,
RecordSource datacontrol Refresh.
ListField bound control,
runtime. , .

- - - - - -- - - - -- - - -

-
.-
243
ListField,
.
. RecordSource datacon-
trol. , SOL,
, :

Data l .Reco rdS ou rce = ~ S e lect [PUDID]& String ( 5, 32 ) & {Name] W &
~As I DNarne. PB~D , Name. Address From Publis he r s "

Datal.Re fresh
DBList l .ListF ield = ~ IDName

DBList l . BoundColumn = ~Name"

SOL, PUBID Name , IDName.


ListField DBList control.
String 5 .
BoundColumn
BoundText control.

D/it/i Grd C:OJItroJ


DBGrid bound control,
,
. control ' data control DataSource.
, control SOL
RecordSource data control ( 11 .5.).
DBGrid control, bound controls.

,
,..
~ -....cn:& ~_~
y_PtiNd ISBN FtIO

~o~_
~l s
.; ~tL~{:~i:f- -~~::!:
-}~;~
~ ~_!o ~ S_QL <I~d_: . j-= ~tt=g:i- _s, .;.."
~2,-.
H tc/H.e ", GUd: VBSO . 1~--~96i242i~ _~7,~
~=~:g:.~ ~~~~i- _ ~7
"~
~~ ~~~'5-5 "53--:'::
~11"Z..~.~ -~::
~~t47I sj~~
}~+-~t- _.t.9";.
Maed~"

An
M sa .. ...
Ad>,orcedY..... B'O: ' .
oo.:I;n to .-.
~

i!i9"o.aiI6082~
jgg;~W.1f5;j_~ --.:~~
9'31Tj:2IJ~ _ - ""
+..
1 ~..!2Oi~ '}~~,~}--- _~L-
An~ to<U:oNse
~~
1"['"'-- "-."...
.... ~~'!.?-:.'!~ .-:r..
lLlI o. , iI!!J

. 11.5. ' DBGrid controI.

DataSource, DBGrid control


, AIlowAddNew, ,
AllowDelete, , Columns.
Column . .

--
. , data control

2 .... - - - - - -- - - - -- - -- -
Refresh DBGrid control, :

Dat a l . RecordSet . MoveFirst


Datal. Re c ordSet. Edit
Da t a l. Reco rdSet . Fields ( l ) " l "

Datal. RecordSet. Update


DBGr i d l. Re f r e s h


. DBGrid control,
design
Properlies. , , Columns property
sheet ( 11.6). '
.

" ..

i K~~ I!'!J ~ t; li.. 1$..,- 1


I lr,;~ CoIumnO ( ponimo] J !!
CQl oo !E ponmo

Dtafekl: IEp~oimo J.,


D ef~6kJe:
M~FCIMI: _ J '.

! ca>o. 1,1 i 1Ji)lJ3 Ilf


. 11.6. ' DBGrid control.

, :

DBGrid l.Columns .Ad d 2


DBGr idl .Columns (2 ).Caption "Ne w Column "
DBGridl .Co l umns (2 J.Vis ibl e True
DBGrid l. Refresh

Drganizer.Vbp Data control text boxes controls bound


DBGrid control. buttons ,
, , . :

, 0

Pr i v ate Su b Fo rffi-Load( )

--
Datal.Databa s eName = App. Pa t h + " \ o r ganize r.mdb"

- - -- - - - - - - - - - - 2 <15 - - - - - - - - - - - - - -
Datal.Reco rdsetType 1
End Sub

\ a

Private Sub Commandl_ Click()


Unlo ad Me
En d Sub

P r ivate Sub Command2_Click ()


Datal.Reco rdset .AddNew
En d Sub

P rivate Sub Command3_Click()


Erro r GoTo errorHandler

Di m Q As String
Dim src As String
Di m c riteria As String
Dim CurrentRcd As Variant

Q ~ Ch r $ ( 3 4 )
CurrectRcd = Da t a l. Recordset. Bookmark
src = InputBox$ (" . " , "Find ")

I f src <> "" Th e n


criteria = "eponimo =" & Q & src & Q
Datal.Recordset.FindFirst c r i t e ria
I f Da t a l . Re c o r d s e t. NoMa t c h Then
Beep
MsgBox " x ~ l "
Da ta l .Recordset.Bookmark CurrectRcd
End I f
End If
Exit Sub
errorHandler:
MsgBo x Error
Exit Sub
End Sub

Privat e Sub Command4_C l ick()


Datal. Reco rdset . Edit
End Sub

--
Private Sub Command5_C lick()

2 46
Er ro r GoTo e r ro rHandl e r

Datal. Recordset. Update


DBGridl.Refresh
Exit Sub

e r r o r Ha nd ler:
MsgBox Error
Exit Sub
End Sub
, ~o

Private Sub Command 6_ Click ()


Erro r GoTo e r rorHand l e r

Datal . Rec or ds et. De l ete


Datal . Recordset. Mov eNe xt
I f Data l . Rec ordset. EOF Then
Datal.Recordset .MoveLa st
End I f
DBGr i d l . Re f r e s h
Exit Sub
e r r orHandler:
MsgBox Err or
Ex i t Sub
End Sub

e dzH, ,1. 11 ,1. , _


' '
Personal Organizer
0"0
-. ."i",. Til_f.". , .
F'oetro;

''''''''

JII:wooi "'l 1
O".m~
; 6 ~ ' p ~

....., ...
6~ .. _ qit i"",
47 !18 ~

_7, 23
-.. .. ,....
/-'"

...
1...- -~ -~
T~

14663'19
","""",

..,

"'"
Ipo:edn@Ico.I g

--.:::J ~ B
~ ~ --=:!J
m; .1
IHI4/D;/II;/I1

. 11.7. Orgaaizer.Vbp.

--
2 47

1. ; ;
2. Tr data contro/;
3. Tr data cantro/ '
;

4. data controI.
5. bound contro/s; .
6. Recordset; .
7. Recordset ;
.

8. contro/s data contro/ Tr


' ;

1. data control, Listbo tetbo controls.


design data control Biblio.Mdb Publishers
Visual BasIc, listbo Company Name tetbo controls
Pu blD, Name Company Name . .
Li stb o control. ;

2. . '
controls , D
time .

3. Organizer.vbp , DBGrid control


M SFleGrid
control, Organizer.Mdb.
, MSFleG rid control (
) .
MS FleGrid control,
bound controls .

- - - - -- - - - - -- -
--
- - 24 8 - - - - - -- -- -- - -- -

, (Database)
" ,
, Excel.
,
; .
, .
. ,
.
, , .. , ,
. . . ,
.
, ,
,
:
.
@! .
@) .
,

C lm nl ,
,
, , , . . .

Rw s/ ( recod) , ..,
(fields) (, , ) -
. , -
.

Re l a n sh / / . ~LK
- , ,
.

--
2 ... 9 - - - - - - - - -- - - - - - -

Database/ , .

/ , , '
, .

Index/ ,

.

,
, .

, , .
, , , , . .
.
,
.

,
. , ,
.

: , , , Fax, , , , , , . .

,
.
. ,

. ,
, ' , .

Fax

--
. , ;

2 50 - -- - - - -- -- - - ---
Access .
, .. , , .
, .
, ,
, , .
.
(keys).
(primary key),
.
primary key
, .
simple key ( ,
- composite key - ( ,
(atternate keys), , .
, primary key ,
.
, bytes
.
, ' ,
primary key, Autonumber.
, ,
.

OrdersTable
Custom ers Table Qrder!D
?ustomerlD CustomerlD
fm;.ign ~ij: ;,
CompanyName OrderOaIe
ConIactNam RequiredO ate
ConlactTi!le EmployeelD
Address Ship e:lD ate
city
RegiOn
Posta!Cooe

. 12.1. CustomerlD Customers


Orders / .

12. 1., CustomerlD Drders foreign key.


, .
, primary key , foreign key Orders
, .

( ll values), , .

( lJJdexes )
,
( ) . ,
,

--
, Indexed :

-~-------------- 251
Yes (Duplicates )
Yes ( Duplicates)

,
(table
sca) ,
, .
,
. ' ,
,
.

:
,
.
(Gompact), .

DAO

Visual Basic (eg ie) , Jet,


Data cot ro l (Data
Access Objects) . Data co tro l ,
,
.
,
idexes , . ,
. Jet
.
,
. ,
Microsoft Access database ' saL Server , .
Visual Basic
Jet:

vt5uuI Bil5LC Dutubil5e5


Jet
Microsoft Access, .

Exterl1ill Dutubil5e5
ISAM (Indexed Se q uetial Access Method) ,
, Btrieve, dBASE 111, dBASE IV, Microsoft FoxPro 2.0 2.5, Paradox 3 .
4.0. Visual Basic (text
files) (worksheets) Microsoft Excel Lotus 1-2-3.

ODBC Dutubil5e5

--
c liet-server, ODBG stadard , Microsoft saL

2 52 - - - - -- - - - - - - -- -
Server. ODBCDirect mode D ODBC
, Jet. , Remote Data Objects (RDO)
Remote Data control (RDC), EnterprIse Visual Basic,
ODBC.

\ 'ILSUff BfSLC 5.0


Visual Basic 5.0 3.5 Jet 32-bit. ,
Jet 16-bi! DAO. , 3.5
, 16-bit.
,
:
ODBCDirect, D ,
ODBC , Jet ODBC .
data bound ActIveX'Mcontrois Visual Basic,
DataBindings.

D ,
. ,
DBEngine .
, ,
. Workspaces (
),
Workspace. Workspace Database.
Database TableDef ..
,
, ' (index) . , TableDef
Database MyDatabase, MyDatabase.TableDefs(O),
MyDatabase.TableDefs(1) . .

DBEnglne
l{ Workspace
Dat..base
L TableDef 1 QueryDef 1 RecordseI 1 Con!ainer J l RelaIi:lr
~ fie ld f ield 1 Fie!d 1 OocnenI 1 Fie!d

Index Parameter
Field
I)re,

lfGroup Legend

and collection

CJ Obje cl on'Y
User

""

. 12.2. OVI KEItVWV .

--
2 53 - - - - - - - - - - - - - -
( ""
, . (dot).

D B E ng i ne.Wor k space s (O ) . D ataba s e s (O) .Table D ef s (O ) .F iel d s ( ~ C u s t ome r " )

Customer, TableDef, TableDefs,


Database, Databases
Workspace, Workspaces DBEngine.
, index,
.
' , ,
! (bang). .

MyTa bleD ef. Fi elds( "Custome r " )


My Tab l e Def . Fi el ds !Custome r

l)

Jet (
D , ( , , indexes
(relations).
Database , TableDef Field .
:
Dim -
. , VK DBEngine default Workspace :
Database.
TableDef .
Field .
Index index .

:

Di m MyDB As Databa s e ,My Ws As Wo r ksp ace


Dim Au Td As Tab leDef, TitTd As Ta bleDef, PubT d As t abl eDef
Dim AuF lds( 2) As F ie ld, Tit Flds ( S ) As Field ,PubFl d s ( 10) As Fiel d
Di m Aul dx As I n de x , Tit ldx ( 3 ) As Inde x , Publ dx As Inde x

t'9 CreateDatabase Workspace


, . :
(Iocale).
. dbLangGreek:
Set Myws = DBEngine.Wo rk s p a c e s(O )
Se t MyDb = My Ws.CreateDatabase("C: \ VB\Biblio .mdb" , db LangGreek)

tI CreateTableDef Database,
TableDef , :

Set TitTd = MyDB. Cr e ate Ta b l e Def{ "Tit l e s" )

~~~~~~~~~~~~~-

--
25 .. ~~~ ~ ~~~~~~~~~-
Set AuTd = My DB. CreateT able De f (~Auth or s " )
Set PubT d = My DB. C re ateTableDef(~P ub li shers W)

CreateReld TableDef,
Reld ; ( , . .) :

Set "AuF lds( O) = Au Td. Creat e F i eld ( ~Au-ID", dbLong)


, n~ o y counter.
AuFlds( O).Attrib ut es = dbAu to lncrField
Se t AuF lds(l) = My Td .Cre at e F i e l d ( ~Author " , db Te xt )
AuFld s(l) .Size = 50

@ Append :

AuTd. Fiel d s . Append AuF l d s { O)


AuTd. Fields.Append AuFlds(l)
MyDB.Tab leDefs. Append Au Td

rl r ~ i YJdex '

indexes .
:
indexes , Createlndex
TableDef, :

Se t Au ldx = My T d .C re a te l nde x (~Aut hor ID" )

Auldx.Primary = Tr ue
Auldx .Unique = True

@ index, CreateField
Index:
Set NewFld = Auldx. CreateFie ld ("Au-I D")

4!) Index Index TableDef:


Auldx .Fields.Append NewFl d
MyTd.lnde x e s . Append Aul dx

CreateField Index
TableDef Index. Type
and Size Index.

(refGItioYJ5)
(RefereYJtiGlf IYJtegritg)
TabIeDefs (keys) primary and foreign,
, ,
primary/foreign. , ,
, . ,

--
, foreign (valid)

--~~--------- 255 - -- - - - - - -----


. , BibliO.mdb Visual Basic,
PublD Tilles foreign, - PublD
Publishers. Tilles PublD
, , 20, Publishers,
PublD 20. , -
(referenlial inlegrity violalion) . .
Jel Relalion.
. :
U Relalion, CrealeRelalion
Database Table ForeignTable:
Dim -it As Relation
Set Au-Tit = MyDb.CreateRelation (UAuthors_Titles ")
Au-Tit.Table = "Authors"
Au-Tit.Fore ignTable = "Titles"

f9 U - primary/foreign ,
CreateField Relation :
Dim TempField As Field
Set TempField = Au-Tit.CreateField ("Au-ID")
TempField.ForeignName = "Au-I D"

@) Append Field
Relalion Database.
Au-Tit.Fields .Append TempField
MyDb.Relations.Append Au-Tit

x~ vnv

D
, .
TableDef Field Index . ,
, index .
SQL,
U .
, :


,
TableDef TableDefs, :

Dim db As Database
Dim NewTd As TableDef ' n ~oo TableDef ~Ko.
Dim NewFld As Field \ n~ovo F ie l d li.

Set db = DBEngine. Workspaces(O ).OpenDatabase ( "Test.mdb" )

Set NewTd = db .C reateTableDef (~ New Tab l e Name" )

-
.-
25 6 - - - - -- - - - - - - - - - -
Se t NewFl d = NewTd.Creat e Fi e ld ( ~N ew Fie l d Name n , dblnteger)

NewTd. Fields . Ap p end NewFld ' o~o ~o Field ~o TableDef.


db.T abl eDefs.App end NewTd ' o~o ~o TableDef ~n Database.
db. Cl o s e ' ~n Databas e .

flivaxa
, Delete TableDefs.
, indexes,
, ' .
Authors:
Db .Tab leDe f s .Delete ~Authorsn

f ' flivaxa
' ,
field Fields.
Address Phone Authors.
Dim Db As Databas e
Dim Td As Tab leDe f
Dim Fld As Field

Set Db = D B E ngin e. Work space s (O ).OpenDatab a s e { ~C : \T est .mdb n)

Set Td = D b.T ab leDefs(~ Author sn )


, nlu ~o ~ o .
Set Fld = T d.C reat eFi eld (~Add re s s n , dbTe xt, 30)
, Field Fi e lds .

Td.Fi elds .App end Fld


, l l Fld ~o Y10 .

Set Fl d = Td . CreateF ield ( " ", dbTe x t , 2 5)


, Field l Fi e l ds

Td. Fiel ds . Append Fl d


Db.Clo se

j f
, ' TableDef.
, Index Relation objects.
Delete TableDef. indexed
Index . Relatian.

po~ lJ)dex ' flivaxa


Append lndex
lndexes. index Authors:
Dim Db As Datab a s e , Td As TableDef, Newl dx As Index, NewFld As Fi eld

Se t Db DBEng i ne . Wo rk s p a c e s (O ) .O p enDat ab as e ( ~C:\ Bi blio .mdb n)

Se t Td Db . T ab l eDe f s ( ~Auth or s n)

~~~~~~~~~~~~~~-
--
257 -~~~~~~~~~~~~~-
Se t Ne wl dx = Td . Cr e a t e l nd e x ( UAdd r e s a-I nde x " )
Newldx.Unique = Fa lse
Set NewFld = Newl dx. Cr e a t eField (UAdd r e s s " )

Newldx. Fi e lds . Append NewFl d \ l Field I nde x


Td . Inde x es .Append Ne wldx \ l I ndex Tabl eDe f
Db.Clo s e

IJJdex
index
. "Address_lndex" index
Indexes Authors:
Db .Table Defs (UAuthors " ) . Inde x e s.D e ! et e uAdd ress_I ndex"

Index Relation.

DAO

.
DAO.

De
DBEngine, ,
Workspace, .
DBEngine :

D BEngine

Wrk ace-
ErrOIS

. 12.3. DBEngine.

DefauItUser / DefaultPassword
User name Password " " MS
Access. Jet ,
User Password
Workspace.

IniPath

ISAM.DLL MS Access.

LoginTimeout
Jet

--
login ODBC.

- - - - - - - -- - - - - - - 258 - - - -- -- - -- - - -- -
Version
read-only m DBEngine .

m Jet, DBEngine
:

CompactDatabase
, RepaIrDatabase, .

CreateWorkspace
Workspace,
.
Workspace, Workspaces.
:

Set variab le = Cr eateWorkspace (name, u ser. pa s sw ord, type)

name Workspace, user


Workspace, password 14 , ,
type Workspace .
:

dbUseJet Microsoft Jet workspace.


dbUseODBC OD BCDirect workspace.

Dim MyWorkspace As Workspace


Dim MyUserName As Str ing
MyUserName = DBEng ine. Work s pace s (O).Use rName

DBEng i ne .IniPath = ~ C : \ MYAP P DI R \ MYAP P . "

Set MyWorkspace = DBEngine.C reateWorkspace ("Special" , MyUserName, "SpecialPW" ,


db UseJet )

IdIe

. transactIon, ,
, CommitTrans m .

RegisterDatabase
ODBCdriver Registry Windows.

RepairDatabase
m MS Access.

--
25 9 - - - - - -- - - - - - - -- -
. Workspoc:e
Workspace
Oatabase.
, Workspace Oatabase, Users Groups.

OBE rg-<e

W'orkspaces

Workspace

. 12.4. VIK Workspace.

, Workspace Workspace,
.
Workspace :

Name
Name Workspace.

Count
Count m Workspaces Workspace.
, Workspace.

Username Password
Workspace, password
.

Workspace .

BeginTrans, CommitTrans RollBack


transaction
, Workspace. BeginTrans transac-
, CommitTrans transaction ,
, , RoilBack transaction
m transaction.
, BeginTrans transaction
Employees . .
Commit Trans , RollBack
. , OpenDatabase
OpenRecordset, .
Fun ction ChangeTit l e
Dim Employ e e Name As Str ing
Dim Message As St r ing , Prompt As Stri ng
Dim My Works pace As Workspace , MyDat abase As Dat aba se , MyTabl e_

--
2 60 - - - - - - - - - -- - - - -
As Re cordset
Prompt = ~ t it le Acc ount Exe cutive ?"
Set MyWo rkspa ce = Workspaces( O) , default Workspace .
, database.
Set MyDatabase = MyWorks pa ce .Op en Databas e (~ MYDB .MDB" )
, .
Set MyTable = MyDat aba s e . OpenRe c ordse t("Employ e e s ", dbOpenTable )
MyWo rk s pac e .BeginTrans , K~o p t ran s act ion.
MyTable.MoveFi r st
Until MyTable . EOF

If MyTable ! [Ti t le ] = "Sales Repre s e nt at i v e" Then


Emp l oyeeName = MyTabl e ! [Last Name] & " , " & My Tabl e !
[Fir s t --.Name ]
Message = "Employee: " & EmployeeName & vbCrLf
I f Ms gBox(Me s s age & Prompt, vbQue s t ion + v bYesNo , ~ Cha n ge_
Job Ti tle" ) = YES Then
MyTable. Edit
MyTabl e! [Ti tle] "Ac coun t Exe cut i v e "
MyTable. Update
End If
End I f
MyTable.MoveNext
Loo p
If a l l change s ?", vbQue s t ion + vbYe sNo,
MsgBox {~ S ave

Sav e Changes") = YES Then


~

MyWo rkspace .CommitTrans E ~ n a

Else
MyWo rkspace.Rollback ~ n

End If
MyTab le.Clo s e ' table .

MyDataba s e.Close
End Func tion

Close
Close Workspace Warkspace.
default Workspace, .

CreateDatabase
, ,
MS Access. :

Set dat aba s e = workspace.CreateDatabase ( databasename, _


locale [, opt i ons ])

databasename , locale
, (;
dbLangGreek ) , , , options

--
2 61

dbEncrypl ( encrypled ) .

dbVersion1 MicrosoftJel 1.0.


dbVersion11 Microsoft Jel 1.1 .
dbVersion25 Microsoft Jel 2.5.
dbVersion30 (l.ll) Microsoft Jel 3.0.
3.5.

database .

OpenOatabase

database. :
Se t da taba s e = wo r ks pa ce . OpenDa t a ba s e{ db name [, e x c l us i ve_
[, read-only [, source ] ] ] )

dbname , exclusive
, read-only
, , , source
OOBC .

Dut ubuse

database. :

Wok;p.'ICe

Dtab.uet

-
O Mab bIcO eI'$ A~"""

""""""
Q .-.le/ $
""""'"

. 12.5. m mv Database.

Oatabase :

CoIIatingOrder

read-only ,
locale CreaIeDaIabase,
. dbSortGreek (
Microsoft.Jet workspaces).

ConnecI
read-only options OpenDatabase.

--
2 62 - - - - - -- - - - - - -----:
Count
Database ] Database.

Name
read-only

QueryTimeout
Database
, query ODBG.

RecordsAffected
read-only (records)
Execute ..

Transactions
read-only TRUE FALSE, Database
transaction.

Updatable

read-only FALSE TRUE, Database

Version
read-only D
.

Database.

OpenRecordset
Recordset ] Recordsets.
" , Recordset
query () . :

Set va r i able = data base.Ope nRecordset (source[ , t ype [, options]] )

ij variable, , Recordset.
, OpenRecordset.

source source recordset ,


SQL QueryDef.
. type recordet .
:

dbDpenTable recordset table (defauh).


dbOpenDynamic recordset, ' ODBC
dynamic cursor ( OOBCOirecI Workspaces).

--
2 63

l (',) dbOpenOynasel recordset Dynaset.


dbOpenSn apShot SnapShot recordset.
options options recordset.
+.
dbO enyWrile
recordset.
dbOenyRead recordset.
recordset dbOpenTable.
dbReadOnly recordset

dbAppe ndOnIy recordset, -


recorset,
J o dbOpenOynasel.
dbConsistent joined recordset, (oneto-many).
.
recordset dbOpenOynasei.
dblnconstistent joined recordset, u , -
ov , . -
recordset dbOpenOynaset.
dbForwardOnIy recordse! dbOpenSnapSho! i
,! .

dbSQLPassTh rough C , saL


recordset serer
vj Access.
dbSeeChange ,
.

dbRunAsync i query ( ODBCDi rect Workspaces) .

, MYDB.MDB VKo
recordseI, .

oim Crite r i a As St r i ng. As Dat aba se, MySet As Recor ds et


oim NewTit l e As St r i ng

Cr ite r ia UT i tl e = ' ' "


NewTi tl e U ~ "' ~ t it l e .

Se t MyDB Workspaces ( O). Ope nDat abas e ( " MYDB. MDB" )


, n ~ o o d yna s e t .
Set MySe t = MyD B .Ope nRecords et ( ~Empl o y e es W , dbOpenDynaset}

MySet.Fi ndF ir s t Cri t eria n .


, ~ x~ ~ .
Until MySet.NoMatch

MySet. Edit ' 0 ~~ K ~ .


MySet !Title = NewTi t le ' .
MyS et.Updat e ' .
MySe t . Fi ndNex t Cr ite ria .
Lo

--
26 4
Cre ateProperty
CreateProperty Database.
, Property (b ui ~-i n)
Database (user-defined).
Set v a r i a b l e = ob j ect .Crea t e Prope rty ([name [, t ype [, val ue [ , fDDL]JJ)

variable Property. name


, type , value
, . , f L
Data Definition Language. RUE,
, (permis-
sion) dbSecWrite.
Property.
Append, Database.
Di m MyProperty As Pro pert y
Dim MyDatabase As Data b a s e

Set MyDatabase = Wo r k spa ce s( O) . Op e n D a t abas e ( ~MYD B. MDBR )

, n~oo Prope rty ~Ko .

Se t My Property = MyD at aba s e .C re a tePro perty (~ P r ivile geW , dbBo ole a n , _


True , False)
MyDatabase.Prope rt i e s . Append MyPro p erty

CreateQueryDef
CreateQueryDef
QueryDef,
. :

Set querydef = database.Cre ateQue ryDef ( [name ] [, sqltext ])

name
QueryDef, sqltext SQL
, QueryDef. , name '" .
Query, .
, QueryDef Pubs SQL
Recordset, Dynaset, query.

Dim MyDB As Databas e . MyQuery As Quer yDe f . My Se t As Re c ordset

Set My DB = Wor ks p ac e s( O ) . OpenD a taba s e( ~BI BLI O .MD B ")

\ 1. 0 Quer y De f .
Set MyQue r y = MyDB. C r e at eQ u e r D e f ( ' Pubs H , "SELECT * FROM Publi shers ; " )
\ Re co r d s e t qu ery.
Set MySet = MyDB. OpenRe co r d set("All Pub s H , dbOpenDynaset )

MyS et .Clo s e ' 1. Reco rds e t.

CrealeRefalion
CreateRelation Relation,

--
queries. :

- -- - - - -- - - - - - - 265 - - - - - -- - - - - ---
Se t vari abl e = databas e . CreateRela tio n([name[, table [, _
fo r e i gntabl e [, attri b ute s ] ] ] ])

variable Relation. name


. table -
(parenttable p rimay table) , foreigntable (child
table foreign table). attributes
. , ,
attributes +.

dbRelationUnique one-to-one .

dbReJationDontEnforce (referential integrity) .

dbRelationlnherited attached ,
.

Relation, parent
, CreateField, child
ForeignName. ,
Customers ValidStates CustState StateCode .
Dim My Re lati o n As Re latio n
Dim My Dat abase As Database
Dim My Fie ld As Field

Set MyDat ab a s e = Wor kspa c e s{ O) . Op enDat abase (~MYD B. MDB *)

\ n ~ouo Relat ion a~ ~K o.

Set MyRela tion = MyDatabase .Create Relat i on{nTableRelation One *,


"Customers" , "ValidStates" )
MyRel at ion .Attribut e s = dbRelationUpdateCa scade
Set MyField = MyRelat i o n.C reateField (" CustState" )
MyField.Fo r e i gnName = "Stat e Co d e"
MyRelation.Fields .Append MyFi e ld
My Database . Re lations.Append MyRe l a t i on

CreateTableDef
CreateTableDef Database. :
Set variabl e = databa s e.CreateTableDef ([name[ , a t t r i butes [, _
source , c onnect]]]])

variable
TableDef. name
, attributes
. , source
, connect
Microsoft Access.
Ttl Detail
, Comments.

Dim MyTableDef As TableDe f , MyFie ld As Field


Dim MyDataba s e As Dat ah a s e

--
266 - - - - - - - - - - - - - - -
Set MyDatab ase = Workspaces (O ). OpenDatabase ("B1BL10.MDB")
, ~oy V ~K ~ O TableDef.
Set MyTableDef = MyDatabase.Creat eTableDef("Title Detail " )
, MyTableDef.
Set MyFie ld = MyTableDef.CreateFie ld ( "Comments" ,dbDat e)
MyTableDef.Fields.Append MyField
MyDatabase .Tab leDefs .Append MyTableDef

Execute
OueryDef SOL Database. '
:

database.Execute source [ , options]

source SOL OueryD ef.


optIons .
m .

dbDenyWrIte -
, Execute.
dblnconsistent .

dbConsIstent .

dbSQLPasshro ug h Jet SQL QueryDet


ODBC .

dbFailonError , ,
.

dbSeeChanges -
SOL OueyD ef.

dbRunAsync ( ) . -
ODBCDirect QueyDef .

, SOL,
Titles.
Dim SQL as String
SQL = "DELETE FROM Titles WHERE ISBN 1S NULL"
. Database.Execute SQL. dbFai lOnError

b l e D ef
ableDef
Field Index.

D<tabase

! OOIeDefs L

11OOleD81 ~ ~elds ml$"i 111

. 12.6. TableDef.

- -- - - - - - - - - - --
--
267 - - - - - -- - - - - - - -
TableDef , DateCreated LastUpdated,
, RecordCount,
. .
.

CreateField
(tield),
TableDet. :
Set variable = o bject .C r e a t e F i e l d ( [ name [ , typ e [, si z e ] ] ] )

variable Field. name


. type , size .
Visual Basic 5.0 21 ,
, size.
5 "

dbBoolean TruelFalse Integer ( 1) 1


dbByte Byte Integer ( 255) 1
dblnteger Integer Integer 2
dbLong Long Long 4
dbCurrency Cue nC Double 8
db5ingle Single Single 4
dbDouble Double Double 8
dbDate DatefTime Vanant 8
dbTeX TeX Stnng 1 255
dbLongBinary Long Binary String

dbMemo Memo Stnng

dbTe t ,
sIze, Visual Basic ,
; . , ,
Phone, MyTable.
Dim MyDat aba se As Databa se
Dim MyTabl e De f As Tabl e Def
Dim My Field As Fie l d

Se t MyDat a b a s e = Work spa ces( O) . OpenDat abase{ ~ MYDB. MDB N )

Se t MyTa b l e Def = MyDa t a hase.TableDefs (n MyTable" )


n1 0O Field .

Se t MyField = MyTableDef .C r eat eF ield(" Ph one" , dbT ext , 25 )


MyTableDef. Fiel d s. Append MyField
Createlndex
Ind e, , ,
. :

Set variable = t a b ledef. Create lndex([name)

- -- - -- -- - - - - - - - 268 - --
-- - - - - - - - -----
variable Index, name
. , Index.
Dim Myl nde x As Index
Dirn MyField As Field
Dim MyTab l e De f As Tabl e Def
Dim MyDat aba se As Da t aba s e

Se t MyDa t abase = Workspaces (Q ) . Open Da tabase (~MYDB .MD Bn)

Set MyTableDef = MyDatabase .TableDe fs ( O)


\ n~o I ndex OV1 K 1 o .
Set Mylndex = My Tab leDe f . Create l ndex( "Anothe r")
Set MyF ield = MyI ndex. CreateField (" La s tName")
Myl ndex . Pr i ma r y = Tr ue
My l nde x . Re qui red = True
My l nde x . Fi e l d s . Append MyFi eld
My Tab l e De f . I nde x e s.App e n d Mylndex

C reaIeProertv
TableDef.
.

OenRecordSet
recordset. OpenRecordSet
TableDef Database, ,
TableDef
source. ,

RefreshLink
linkedtable,
.

feId
Field ()
.

I~ QueyDeI. R~eL

~eMtor bIeOeI
F,e lds

Feld

. 12.7. VIK o Field.

Field.

AIlowZeroLength
(" ),

- - - - - - - - - - - - - -
--
269 - -- - - - - - -- - - --
At!ributes
.
.

dbFixedField . default .

dbVariableField U . default .

dbAutolncrField Long Integer , .


Microsoft Access.
dbUpdateableField .

dbDescenting Field Index,


i (desce nding order).
dbHyperlinkField i hypenink i ( i Memo).

DateUpdateable
.

Defaul!Value
, .

FareinName
VKo Field foreign table, primary table.

Name
Field.

DrdinalPosi!ion
Field .

Required

Required # NULL#.

Size
bytes ,
( , dbText
255 ).

SourceField
attached.

SourceTable
attached .

Type
.
.

-
.-
27 0 ---~------------
, , Fax Phone,
Employees dbText, 20 .
Di rn MyDat abase As Databas e
Dim My Field As F ie l~ MyTabl eD ef As TableDe f

Se t My Data b a se = Wo r k s pa ces( O). Ope nDat a b a s e( ~MYDB . MDB ~ )

Set MyTabl eD ef = MyDataba s e ! Employees


\ hn~ u Fi eld V l K .

Set My Fi e l d = MyTab l e Def.Crea teF i e l d( ~Fax Phon e n )

, 1 6 .

MyFie ld.Type = dbText


MyFi e l d.Siz e = 20
MyTableDe f.Fields .Append MyFi e l d

, CreateField,
:

Se t MyF ie ld = MyTabl eDef .C re ate F ie ld (~F a x Ph one" , dbTe x t , 20)


255
, Memo, 1.2 Ge. ,
dbLongBinary, OLE.
, Visual Basic ,
.

AppendChunk .

FieldSize .

GetChunk .

AppendChunk :
f i eldo b jec t. Append Chu nk s o u rce

source fieldobject.
Memo Long Binary
AppendChunk data control, .
:

Sub Pas t e Bi g File (FNarne As String)


Di m To talS i z e As Long, Cu rChunk As St ring
Dim As I n teger , FNum As Int ege r , Chun kSi z e As Intege r

Chun kSi z e = 12000 .

Dat a l . Re co r d Se t. Edit Ed it (~) .

\K~ Comments .
Da t a l. Re cord Se t . Fields ( "Commen ts H )

--
FNum = FreeFile

- -- - - - - - - - - -- - - - 271
Open FNarne For Binary As #FNurn ' .

Tota lSize = LOF ( FNum )


00 Whi le Not EOF {FNum)
If TotalSize - Seek(FNurn ) < ChunkSize Th en
ChunkSiz e = Tota1S ize - Seek ( FNum ) + 1 0
End If
CurChunk = St r i n g $ ( Chu n k Si z e + 1 , 32 )
Get 'FNum" CurChu n k ' 2
If I n St r ( Cu r Chun k . Ch r $ ( O > Th en
Cu rCh u nk = Le ft $ (Cu rCh u n k , InStr( CurChunk , Ch r $ (O - 1)

End I f
Cornment s.
Data1 .RecordSet. Fields( ~CommentsW) .AppendChunk ( CurChunk)
Loo p
Oata1 .RecordSet . Update 2 .

Clo s e FNun 2 .

End Sub

FieldSize :

sizev ar = fi eldobj ect.Fie1dSize(

GetChunk:
stringar = f ieldobject.GetChunk ( offset , numbytes )

offset numbytes
bytes .
GetBigFile ,
Memo Long Binary.
Su b Ge tBigFi 1e ( FName As String )
oirn NumChunks As Lo n g , To t al Si ze As Lo n g
o im RemChunk As I n t e g e r , CurSize As I nteger
Oim As Int eger, FNum As Int e g e r, CurChunk As String

ChunkS ize = 2 0 0 0 \ .
, . Cornments.
TotalSize Oatal.Reco rdSet.Fie1ds (~C ommentsH ).F ie1dSi ze()

NunChunks = Tot a1Size \ ChunkSize \ 2 2.

, b yte s 2 .
RemChunk = TotalSize Mod Ch unkSize
CurS i z e = Ch u nkS ize
FNum = Fre eFi1e
Op e n FNarne For Bi nary As f FNum \ . .

F or = N unChunks
I f = NumChunks Th e n CurSize = RemChunk
CurChunk = Datal .Rec ord Set.F ie1ds( ~Comments) .
Get Chunk(I* ChunkSize, Cu rSize)

--
Pu t #F Nun" CurChunk ' .

2 72
Ne xt

C!ose FNum
End Sub

A~ ~o / Index
Inde
.
.
Inde .

Foreign
Ind e m ' foreign .

IngoreNulls

Required Ind e #NULL#.
FALSE, Required, ,
TRUE.

Name
I nde .

Primary
in d e "
mary key" , . Microsoft Access
"primary key", .
Ind e Primary In de.
Inde "primary key" TRUE/FALSE , ,
# NULL# lnde.

Required
, i nde ,
#NULL.

Unique
:
lnd e. , TableDef
Field Primary I nde, Field.
, TableDef Field.
primary i nde,
Field:
Dim MyDatabase As Database
Dim My Tab! e De f As TableDef
Di m MyFie ld As F ie ld, Mylndex As I ndex
Dim As I nteger

\ n~oyo .

--
2 73 - - - - - - - - -- - ----
Set MyDatabase = Worksp ac es ( O) .OpenDat ab ase(~MyDB .MDB")

Set My Tab l e De f = MyDatabas e .CreateTable Def(~MyTabl e" )


Set My Fie l d = MyTa ble Def.Cre at eField( ~Fi eldl" , db Long)
\ ~ o 1 1 .

MyField. Require d = Tr ue
MyTableDe f . Fie l d s . Ap pend MyF ield
Set MyFie l d = MyTable Def. CreateField( ~Fi eld2 w , db Long)
\ 1 1 1 Nul l 1 .
MyF i e ld Requ ire d = True
MyTable De f . Fie l d s.Append MyField
My Databa s e . TableDefs.Append MyTable Def
, n1 0 p r imary i nde x ~
Set Mylnd e x = My T ab l eD e f .C re a t e lndex (~ My l nde x* )
Myl ndex . Pr imary = True
Myl nd ex .Unique = True
Se t MyFi el d = My TableDe f .C re a t e Fi e l d (~ F ie l d l)
Mylnd ex. Fields. App end MyField

Set My Fi e l d = My Tab leDef . Cre ateF ield(~F ie ld2 n)

Mylndex.Fi e lds .Append MyFi e l d


MyTableDef. I nd exes.Append MyIndex

Recordset table index.


Index, .
Dim DbAs Database
Dim MyTable as Recordset , MyIndex As Inde x
Dim As Integer

Set Db = Wo rkspaces (O ) .Op e nD at abase (~MyD B.MDB" )


Set MyTabl e = Db .OpenRecord s et ( "Tit les ", dbOpenTable )
MyTabl e. Index = "Mylndex"

v(v QueryDef
SQL
, QueryDef.
QueryDe! RecordSource data control. QueryDe!
Field Parameter. query
(action query).

D._ . ..<
QueJrDels

\"_,0", P", Oete


'''''' .1

. 12.8. QueryDef.

--
; QueryDef.

2 74
DateCreated LastUpdaled
/
DateCreated Que yD ef ,
LastUpdated / .

Name
Q u eyDef.

RecordsAffected
action
quey Q ueyDef.

ReturnsRecords
/ QueyDef, / ,
action quey .

SDL
/ / SQL Que yD ef.
, q uey Orders.
Dim MyDB As Databas e , MyQuery As Que r yDe f . MySnapshot As Rec ordset
Se t MyDB = Workspaces( O). OpenDatabas e( -MYDB.MDB W }
n ~ oo q uery.
Set MyQu e ry = MyDB.CreateQueryDef (nLarge F reight" )
MyQuery.SQL = ~S E LE CT * FROM Orders WHERE (F re ight ] > 10;"
\ n ~ oyo s n a p s h o t .
Set MySnap sho t = MyD B .Op e nRe co r ds et (~Large F r e i ght " , dbOpenSnapshot )

Type
Qu eyDef . ,
, action q uey . .
, / Append /
Qu eyD ef, / Close, / q uey,
/ Oelete, Qu eyDef , / Execute,
action quey, / OpenRecordSet / CreateProperty.

i'r.rr.rneter
Parameter
Qu eyD ef. ; / Count,
Parameter, / Name, /, / Type, /
( dbTet , dbDate, dbMemo ..).
, qu ey , ,
, Record set Qu ey D ef.

Dirn MyDB As Database


Dim MyQuery As Que r yDe f , MyParameter As Pa rame t e r
Dim MyReco rdset As Recordset

- -- - -- - - -- -- - - - -
--
275
Set MyDB = Work spaces(O) .Databases(O)
, v QueryDef.
Set MyQuery = MyDB.QueryDefs(UParamQuery ")
, .

MyQuery.Parameters (UOrder Date") = uI0 /4 /97"


MyQuery.Parameters (UShip Date") = u15/4 /97"
, Recordset.
Set MyReco rdset = MyQuery.OpenRecordset()

MyRecordse t.Close

! Recordset
Recordset
, ;
data control.
Recordset query.
12.9, Fields.
Recordset (dbOpenTable, dbOpenOynaset
dbOpenSnapShot), .

Dalabdre
Recobet:
;)
l:'Wd:eJ.F~ ]:1

. 12.9. QueryDef.

AbsoslutePosiIion
Recordset.
BookMark
, AbsolutePosition.
, recordset (n)
. RecordCount,
, MoveLast
RecordCount.
Function MoveToRecord ( as Long, Rs as Recordset) As Integer
RS.MoveLast
If Rs.RecordCount > Then
Rs .AbsolutePosition =

MoveToRecord = Tr ue
Else
MoveToRecord Fa lse
End ! !
End Function

--
2 76 - - - -- - - -- -- - - --
BOF EOF
BOF, TRUE,
Recordset, EOF Record set.
, Recordset , ']
MoveNeX, MaveLast MovePrevious, .

Dim MyDB As Database, MyTable As Reco rdset

Set MyDB = wo rkspaces (O ) .OpenDat abase (~MYDB .MDB" )


r e c o r d s e t
Set My Ta b le = MyDB. OpenRecords e t (UOrders" )

Until MyT ab le .EOF


MyTabl e . MoveN ext ,

LOOp

MyTabl e . MoveLas t
0 0 Unti l MyTable.BOF
My Tab l e . Mov e Pre v ious to pre vio us r e c o r d.

Lo

MyTab le .Close , r e c ord set


MyDb.Close

Bookmark
'] , Recordset. ,
,
Bookmark. '] string variant.
, Recordset
Bookmarks string, .

Functio n FindYear ( YearWante d% . Rs As Records e t , Found() As _


String ) As Integer
Dirn i As I nt e ge r
Rs.F indFi r st n[Yea r Published] = & YearWanted
I f Rs .NoMatch Or Rs . Bo okmarkable False Then
FindYear = False
Exit Function
Else
00 Unt i l Rs.NoMatch = Tr ue
Found(i ) = Rs.800kma rk
Rs .FindNext ~ [Year Published ] ~ & YearWan t e d
i = i + 1
Loop
End I f
FindYe a r = i
End Fun c t i o n

BookMarkable recordset

--
Bookmarks.

2 77
DaleCreated, LastUpdaled LastModilied
DateCreated Recordset,
LastUpdated , , , LastMadilied
Baakmark .

Index
Index, Seek
, .

Dim Tb as Recordset, Db a s Dat aba se


Set Db = Workspaces(O ) .OpenDatabase (" BIBLIO.MDB")
Set Tb = Db. Ope nRec o r d s e t ( "Ti tl e s", db Ta b l e)
Tb.lndex = "PubID"
Tb. Seek "= ", 3

LockEdits
MicrosaIt Access,
Edit. Visual Basic .
2 . default
Edit "pessimistic". .
, Update,
.
,
''ot m st c'' , .
LackEdits . :

re c o r dset. Lo ckEdit s [= {Tr ue Fal se )]

(default), "pessimistic", False


"tmstc " .
, ,
Table Dynaset. .

NoMatch
Find Seek
.

RecordCound
Recordset.

50rl
Sort Recordset, ORDER
SQL . default ,
. ,
Record set data control Ship Country.
Datal.Reco rdset . Sort " [Ship countryJ"

Data l.Recordset . So rt " [Ship Country] Asc

--
Data l .Re cordset .Sort " [Sh ip Count ry] Desc " i

------------~-- 2 78 - - - -- - - - - - -- - --
Transactions

Transactions recordset eeginTrans,
CommitTrans RollBack.

Type
Recordset,
dbOpenTable, dbOpenOynaset dbOpenSnapShot.
Recordset Dynaset SnapShot.
AddNew, Ed t, Update, Oelete, Find, ..,
. Dynaset
. ,
Index. ,
. Dynaset,
Dynaset. Recordset Snapshot
; ,
AddNew, Update . . ""
, Snapshot .
Recordset.

AddNew
Recordset,
SnapShot. , Customers.
, Update . ,
LastModified .

Dim MyDb As Data b as e , MyTabl e As Recordse t

Set MyDb = Wo rks pace s (O ) . Ope nDa t abase(~MYDB .MD B" )

Set MyTabl e = MyDB.Ope nRe cordset ( ~ Cus tome rs ~ . dbOpe nTabl e )


lrn.~
MyTable .AddNew
MyTable (~Cu stomer 1D" ) = ~MicOl"

MyTable("Cornpany Name" ) = "Micro Land"


6

MyTable .Upd ate


MyTab le .Move , MyTa ble . La stMo d i f ie d


MyTable . Delete ' 1 0 re cord
MyTabl e . Cl ose
MyDb.C lo se

CancelUpdate
Recordset Edit AddNew.

CIone
Recordset, .

--
, Recordset,

2 79 - - - - -- - -- - - - - - - -
, , listbox controls.
.

Dim Db as Dat a b ase


Dim Rs l a s Re cordset , Rs2 as Re c o r ds e t

Se t Db = Wo rkspaces( O). Ope nDataba se ("BIBLI O.MDB W )


Se t Rs l = Db.OpenReco rdset( "SELECT * FROM Titles "
& " WHERE [Year PublishedJ > 1995 ORDER by Tit le W
, n1 0O av ~ o reco rdset
Se t Rs 2 = Rsl.C l one ()
Rs 2.MoveF i r s t \

0 0 Unt i l Rs l . EOF
List l .Addl t e m Rsl!Author
Rs l .MoveNe xt
Lo op
00 Unti l Rs 2. EOF
Lis t2 .Addl t em Rs 2!T i t le
Rs 2 . Mov e Ne x t
Loop

CIose
Recordset,
Recordset. .
Dim My Da t a b a s e As Dat abas e . MyRecordset As Re c o rdset
Set MyDatabase Workspaces{O) . Ope nDa t a ba s e (" MYDB. MDB W }
=
W
Set MyRe c ords e t = MyDatabase.OpenRecordse t ( "Customers )

MyRe c o rds e t . Cl ose r e c o rdset


MyDat ab as e . Clo se

CopyQueryDef
,
Recordset. Record set table.

Delele
Recordset
Snapshot. , ,
, .

MyRe c o rds et.FindFi r s t "PubNum = 15 "


\ l

I f Not MyRe c ordset.NoMat ch The n


MyRe c o rds e t . De l ete ' ~l

End I f

Edit
.

--
, Update .

2 80


, ,
Title.
Dim Cr it e r i a As String, NewT i t l e As String

Cr ite r i a = ~Title = ' Ri ght Hand'# . .J.. .

Ne wTit l e = ~My Ri ght Foot # n 1 0 .. .

MyRe cordset . FindFir s t Cr i te r i a

0 0 Wh i le Not My Re cordset . NoMatch


If Not Dat a l. Re c ords e t . NoMat c h Then
MyRe co r ds et . Edi t
MyRecordse t . Fi e l d s("Tit le") = NewTit le
MyRecordset . Updat e
End If
MyReco r d s e t .FindNe xt Crit eria
Loop

FindFirst, FindLast, FindNext Fn d Pre vi ou s


, , .
, NoMatch ,
FALSE, . ,
.

Dim MyCri t e r i a As S t r i ng , MyDB As Da t abase, My Se t As Reco rdse t


MyCr i ter i a = "St a t e = ' Ny , n , J.. . .
Set MyDB = Wor ks pac e s ( O). OpenDat abas e ( "BIBLIO. MDB")
Se t MySet = MyDB . Ope nRe cordset( "Pub l i s hers" ,dbOpenDy na s e t )
My Set. Fi ndFi r st MyCr ite r i a
I f My Se t.NoMat c h The n...

MySet . FindNext MyCriteria '

Move
IOWs .
:

re c ords et.Move rows{ , sta r t]

star1 bookmar1< OWS


bookmark. MoveRelative
.

Sub Mov e Re l at i v e ( Di s t anc e As Long, Di r e ct i on As String, MyRe c o rdset


As Re c or ds e t , Re l at i v eBoo kMark As Str i ng )
Dim Here As Str ing
Here = MyRe c o rdse t. Bookmark
Di re c t i on = UCas e (Di rect ion )
Selec t Case Di rection
Cas e ~FWD " : Dist anc e = Abs( Di s t anc e )

--
Cas e "BACK": Di s t anc e = Abs (Dis t ance ) * - 1

28 1
Ca s e Els e: Ms gBo ~ I n c orr ec t call i ng a rgurne nt"
End Se lect
If UCase(Re lat i veB ookMark} = ~ H E RE w Then
MyRe c ordset .Move Dis t ance
Els e
MyRe cordset. Move Distanc e , RelativeBookMark
End I f
If MyRec ordset.EOF Or MyRecordse t . BOF Then Beep
End Sub

MoveFirst, MoveLast, MoveNext MovePrevious


, ,
, , Recordset.
Recordset,
.

Dirn MyDB As Dat aba s e , MyTabl e As Re c o r dset, SQL as St r ing


Set MyDB = Works pa c es (O).O pe nDa tabase (" MYDB.MDB" )
SQL$ = "Se l e ct * FROM Ernplo ye e s WHERE Title = ' Sales Repre s e nt a tive'
Se t MyTable = MyDB.OpenReco r ds e t (SQL$, dbOpenDyn a s e t)
Unti l MyTable.EOF ' Begin l.
MyTable. Edit ' Enabl e e diti ng.
MyTable !Title = ~Acc ount Executive w
MyTable. Updat e
MyTable.MoveNext

Loop
MyTabl e .Close
MyDB.C los e

OpenRecordSet
OpenRecordSet,
. VKo Recordset
Iable, dynaset snapshot.

Seek
V Ko Recordset table
VKo Index. v :
tab l e . Se ek co mpa r i s on, ke yl , key2 .. .

comparison "", "<> ", " = ", "> >", ">"


, key, key2 .. voxo Index.
, Index Index.
:

Dim MyDB As Databa se, MyTable As Recordset


Set MyDB = Works paces (O ).OpenD atabase(~BIB LIO.MDB W )
t able.
Set MyTabl e = MyDB.O penRecords et ( "Publishe rs ",dbopenT able )

--
2 82
MyTable . Index = "Pr i ma r y Key " , index .
My Tab le.Seek "= ", 3
If MyTable .NoMatch Then.. .

Update
Update Recordset
AddNew Edil.

SQL

SOL (Structured Ouery Language) , ,


,
,
SOL RecordSource data controi.

SOL.
, SELECT,
. FROM
. ,
WHERE.
, (*),
, ,
Publishers.
SELECT Publishers . * FROM Pub lishe r s

AS, ,
:

SELECT (Ye a r Publis he d ] AS Yea r FROM Tit1es

,
brackets.
SELECT (Yea r Published] . Tit le FROM Tit les

,
WHERE.
SELECT publishers. * FROM Pub 1is he r s
WHERE ( Pub l i s he r s . Pub I D > 100 );

,
. :

resul t = expre s s i on Li ke pattern

expression pattern, , False. pattem


wildcards, ?, * ..

SELECT t it le , AU_ ID AS newf ield


FROM Tit l es
WHERE Ti tle LlE ' *SQL* ' AND AU-lD <52

--
2 83 - - -- -- - - - - -- - - -
,
, :

SELECT * FROM Auth ors ORDER Authors.Autho r

,
.

SELECT " Name , ' ' AS , Addre ss FROM pu b l is he rs

,
.

SELECT Tit l e , Au-ID * 10 AS FRQM Titl e s

\} (Aggregfte fUI1Ct0I15)
SQL ,
, , ..
.
COUNT () ov
. , ,
Titles.
SELECT COUNT (Au-ID ) FROM Ti t l es

SUM , AVG,
, .
GROUP ,
, ' . ,
City.
SELECT City, COUNT (Name ) FROM Publi sher s GROUP City

n

.
, xoov .
FROM, WHERE.
.

SELECT Titl e , [Yea r Pub l ishe d] , Aut ho r


FROM Titles. Aut ho rs
WHERE Ti t l e s . AU_ID = Autho r S.AU_ID

It
, '
, dBase, Paradox .. , .

SELECT CUSTOMERS.Cu s tomerID,


FROM CUSTOMERS

--
~C :\DBASE\ DATA\S AL E S " ~ dBASE I V;"

- -- - - -- - - - - - - -- 284 - - -- - - - - - - - - ---
WHERE CUSTOMERS.Customer ID Like ~ A*"

n !JPDATE
SELECT , UPDATE
WHERE, . ,
SET, ,
Freight Orders, WHERE.

D Orders
SET Fr e i g ht = Fr e i g ht * 1. 03
WHERE [Ship Country] = 'UK'

DHETE
UPDATE, DELETE ,
WHERE.

DELETE FROM Employees WHERE Title = 'T rainee'

. nj
MS Access,
"Type Mismatch". ,
(#).
, RecordSource
data control :
Dat a 1. Da t a Ba s e = uC: \ACCESS \NWIND.MDB"
Dat a 1. Re c o r d So u r c e = uSELECT * FROM Employees
WHERE [Bi r t h Date] > #12 /31 /60#"

FindFirst data control:


Data1.Reco rdSet . FindFirst U[Hire Date ] <= #9 /21 /92#"

.nj n
,
:

PARAMETERS parametertext datatype

parametertext datatype .
, Enter state .
PARAMETERS [Enter s t a te ] , Text
SELECT DISTINCTROW Titles . Tit le , Tit l es . [Ye a r Published] ,
Authors.Author, Publishers .Name AS Pub lisher ,
[Ci t y ] & U," & [State ] AS Location
FROM ( Publ i s he r s RIGHT JOIN Tit les Publ ishers .PubID Titles.PubID)
LEFT JOIN Authors Titles .AU-JD =Aut ho r s. Au-I D
WHERE Publ ishers.State=[ Enter state ])
ORDER Tit les.T it le
OWNERACCE SS ;

--
2 85 - - - - - -- - - - - - - - - -
- "

Iistbnx cnntrnI
Iistbox combobox control
. , FieldControl
cmb controI, tabI , , fiId,
control. RT
Database .

Sub F i eldContro l (crnb As Con t rol , tabl As Strin g , fil d As String)


Di m Snpm As Rec ordset, As St ring
Local Erro r Re s ume Next

cmb.Clear: Sc reen. MousePoi nt er : 11

1 0 V 1 K o Recordset
que ry Vl0
tabl. Recordset
V10Olx f i ld 0

Set Snpm = RT . OpenRe c ordset{ ~Sele c t [~ + fi ld + ~] f r om [~ + t abl + ~]

ORDER [~ + fi ld + ~] W , dbOpe nSnapshot)

, cmb 6

fild.
I f Snpm.RecordCount Then
Snpm. MoveFi r st
Do Until Snpm.EOF
v l = Tr im$( CStr (Ass ign( Snpm( O))))
! vl <> " " Th en cmb. Addltem vl

Snp rn. Move Ne x~ .


Loop
! crnb.ListCount > Then cmb.Listlndex

End If
Snpm. Close
Scree n. Mous ePointer 1
End Sub

~ x . 1 #NULL# ~ ov

. .

Function As s ign (St uff as Variant ) as Var i a nt


If I s Nul l( St u f f) Then
As s i gn
Else
As s i gn Stuff
End !
End Function

--
2 86 - - -- - - - - - - - - ---

Info.Vbp, , ,
Iistboxes controls
, queries , Indexes . .
, ~ K ~

Dim db As Da tabase

Private Sub CommandL-Cl ick ()


Dim dbname As St r ing, Td As Tabl eDef. j
Dim Prop As Property

Lo c a l Error Resume Next


db . Clos e
\ E ~ o

CmD ia log l. Fi l t er = ~ Acc ess (* . MDB) I *. mdb IBtr i eve


( *.DDF ) I* . ddf ldBa se ( *.DBF )j* . dbf IF oxP ro (* . DBF)I *. dbf I Pa r a d o x
(* . ) 1* . db"
CmD i alog l . Ac tion = 1
dbname = Tr i m( CrnDia l ogl . file n ame) : I f dbnarne .... " Th en Exit Su b
Se t db = Wo r kspa ce s( O). OpenDatabase( dbname)
Lis t l .Cl e a r : List2.Clea r : List3. Cl ear
Lis t4. Clear : Li s t 5. Cl e ar: List 6.Clear
l istbox .
MS Ac c e s s 1 ~xo o~ o default
~ .

Ko~ .
Fo r j = db. Tab l eDe f s.Coun t - 1
Set Td = db.Tabl eDe f s ( j )
( Td.At t r ibut e s And db SystemObje ct) Then
Li s tl. Addltem Td. Name
End
Next
Li s t l. Li s tCount > The n Lis tl. Listlndex

\ ~ ~ ~
For j = db . Prope r t i e s .Count - 1
Set Prop = db . Prope r t i e s ( j )
Lis t5. Addl tem Prop.Name + ~ = ~ + CSt r (Prop.Value)
Next
\ que r i e s
For j = db .QueryDefs .Count - 1
List 3. Add l tem db . Que r yDefs (j ). Name
Next j
, Relations
For j = db . Relat ions . Count - 1
Li s t 4. Add l t em db . Rel at i ons (j ). Name
Next

--
2 87
End Sub

1 1 10 1is tbox
i 1 inde x 1 1
\ 1 .

Private Sub List1-DblClick()


Dim Td As TableDef.
Lis t2.C lea r : List6.Clear
Se t Td = db . Ta b l e Defs ( Li s t l. List (Listl .List Index
For = Td.Fie lds.Count - 1
List2 .AddItem Td. Fields (I). Name
Next

Fo r
= Td. I ndexe s . Count - 1
List6.AddItem Td. Indexes(I) . Name
Next
End Sub

Private Sub Command2_C l ick()


Unload Me
End Sub

".U"''P;e~
Q;tQl'l1e~
0'0010
CustQI'I1erlD

E mJo,ees E m ~el D
Order Oetail~ Orde!DeIe
RequredDele
S/pedJeIe
ShpVa

A elelorIs
CmtomelD CetegoriesProducts
CWQmesr(\:,rs Cu~t~sO rdes
E mlQY"'el D E mpfojeesO rders
mlo~e~(ders OrdelsOrder Detals
OrdeIDete PJuctsOrder O e!~s
PlimeyKey Shippe' sO rdes
Shped)eIe SIJ P pie sProducl.~
, _

PIopl ties Queies


_ . C\Pogr~ FilesOevSIIJC '" ~betCalli!>l PodlJcts
C~ct
TIensctions. True
C,"""
C<t~S~S lor 1995
Upd3teble . /J., ClJlleI1t Podc t
CQle!ngOder " 1033 ClJi>lOf1\eIS <ind Supplers b9 C~~
~:~~~~ .60 .=J f.=: e s<es b9 Ccrtly .=J

. 12.10. .

'
'
, , (
) . Oatabase , -

--
2 88
, l D RTDB,
TableSource TableTarget. ;

Sub Cop yRe co r d s (Tab l e Sou rce As Stri ng , TableTarget As St r i ng )


Dim Snpm As Rec o r d s et. Snpml As Rec ordset , k

Se t Snpm ApplDB . Op enReco rdset(~ Sel e ct * f rom ~ + Ta b l e Sou rce , _


=

dbOpenSnapshot)
Se t Snpml = RTDB.OpenRecordset(Tabl eTarget. dbOpenTable)
! Snpm.RecordCount Then

Whil e Snpm.EOF = Fa l se
Snp rnl . AddNe w
Fo r k = Snpm.Fields.Count - 1
Snpml( k) = Snpm( k )
Next
Snpml . Updat e
Snpm.MoveNe xt
Wend
End If
Snpm. Close: Snpml .Cl os e
End Sub

Ouery
, C reateOu er Def
"", Quer, . ,
, ,
Field1 Table1 1.1. Quer
, .

Dirn TempQ As QueryDef


Set Te mp Q = My Db. CreateQueryDef ( "" , "Update Tablel Set _
Tablel. Fie ldl = F ie ld l * 1.1; " )
TempQ. Ex e c u t e
TempQ.Clos e

10 Ouery
Quer To p .Vb p , Select,
1 ( ) Q uer.
:

P r i a t e Sub Commandl_ Click ()


Dim MyDB As Database , MyQue ry As QueryDe f . MySet As Rec ordset
Dim Sq l $, QueryDefName$

QueryDe f Name$ = "TopTi t l e s"


Sql$ = " $ELECT 10 Titles . * FROM Tit l es; "

, Ao ~ Da t abase , K~ nl 0 ~l Querydef
Se t MyDB = Workspa ces ( O). OpenDat aba s e (~BIBL IO. MDB" )

- - - - - -- - - - - - -
--
289 - - - - - - - - - - - --
Set MyQue ry = MyDB.CreateQ u eryDef{QueryDefName$ , Sql$)

n~o~ Recordset a Query Ka~ ao

Set MySet = MyDB.OpenReco rdset(QueryDefName$ )


MySet.MoveFirst
While MySet. EOF = False
Print MySet(O )
MySet .MoveNext
Wend

, objects ~l QueryDefName$
MyDB. Que ryDefs. Delete Qu e ryDe f Name $
MyQue ry. Close
MySet.Close
MyDB.Close
End Sub

Query
TableQueryExists.Vbp ExistsTableQuery,
Query
True, . :

Di m D As Database
Function ExistsTableQuery(TName As St r i n g ) As Boolean
Dim Test As String
Const NameNot lnCo llect ion = 3265

Error Resume Ne xt
, Ex~ Name TableDefs .

Test = D . Tabl e De f s ( TName ) . Name


If Err <> NameNotlnCol lect ion Then
Exists TableQuery = True
, Reset erro r
Err =

Name 1 QueryDefs .

Test = D. QueryDefs ( TName$) . Name


I f Err <> NameNotlnCollection Th en
ExistsTableQuery = True
End If
End If
End Function

, . .

P rivate Sub Fo r rn-Cl ick()


Se t D = DBEngine.Workspaces ( O).OpenDatabase(U Biblio.mdb")
Print "BadTab le " ; I I f (E xistsTableQuery ( " BadTableName"),
"does" , " d oe s n ' t " ) ; " e x i st."
Pr i nt "Authors u; I If(ExistsTableQuery(UAuthors" ) ,
"does" , "doesn't" ); " e x ist ."

--
End Sub

29 0

1. tetbax
Listbax c . Laad
BibIiG.Mdb (
VisuaI Basic).
SOL tetbax c l Enter,
Recardset SOL Listbax !

2. TreeView, CammanDiaIag CammandButtan cl'


controls,

. , , TreeView C ,
. .

3. . , ,
TreeView C Oueries ' SOL .

4. 1 .
MSFIexGrid Listbax c l' c
. , .

5. Custamers.Mdb,
Kadikos. Epanima, Onama, Tilefna EmaiI Index .
5 tetbaxes cantraIs , MSFIexGrid
c buttans New. Update Load
MSFIexGrid c
.
MSFlexGrid cl. MSFIexGrid c ,
cantraIs.

- - - - - - -- -- - - -- -
--
29 1

4.0 5.0 Visual Basic


,
.

, ' .
, . ,
ImpIements, .

r; r;r; (object)
' .
,
controI .
, ,
, . Visual Basic,
, .
, ,
, .. , , , ,
, , , , .
, . ,
() , (1997), ( Rena u ~) ,
(5) . ,
.

.. ,
, , .
, Tetbo x, label ..
Visual Basic, .
, , textbox
:

Te xt l .Top = 4 00

- - -- - - - -- - -
--
- - - - 293 - - - -- - - - - - -----
.
, :

object.pr ope r t y = exp re s s i on

, :

var iable = ob j e ct. p roperty

,
With...End With, :

Wi th Label
. Height = 2000
. Widt h = 2000
. Capti on = " Th is i s MyLabel"
En d Wi t h

LabeI ( control).
. , "
" ' , Refresh, " "
Picture ( controI) :
Picturel . Refres h

Addltem, listbox control:


Li st l .Add l t em "Dat a"

,
Object Browser, F2 View .

ObIec! Browsel !![!] f3

J<AI~ Libr~ries;> 1];1 ; :i;1~1 ft.J


r====":;:iJijf.:'J'E
Classe$
Q ~Ili2.~~
,riJJ AlignConstants
' iP AIgnmentConslanIs
, ~ Amb i e n !P ro p e r1i e s
-
Me mber~ QG:!gIbal s ""
~ c~ - AbS
~
A~ AppAcIVale
,~ Asc
-
J
! ~ ',~ AscB

l
')1 Applic a1io nStar1Con~ () AscW
~ AsyncProperty ,~ 1
,fi'1J Async Type co nstanI ~ ..() 8

!,u; 8ordet'StyleConstanl ~ Calendar


IrilJ 8 uttonConslanl s :=.J ,() CBool
",< l li bra e s > JI

. 13.1. ObjecI Browser.

13.1., ,
, ' ,

2 9"
--

VT1 (collection abjects),


.
, ,
, Controls
listbox:
For Each Cont ro l Forrnl.Controls
Listl .AddI item Co ntro l . Name
Next Cont r o l

.
, :

Controls ( "Te xt l n )
Controls!Text l

, :

Controls(3)

Visual Basic , Forms,


, Conlrols, controls , Printers,
.

,
class modules () .
, , .
class modules tarms,
. class module .
Sub Functions , Public,
, Public, declaration modle ,
, .

i,. .. .,,'
,':'-: ".
CJ.s I CIMsMocUe

co ;;ou;<!
""'"
Priolote
.
P.bkNot<retble
:) - Sh;IeUsI!

6' ~

:,;,;:;, _. - -
y"ttwt.~~)'CUUI_

. 13.2. .

Projecl Visual Basic, Add CIass Modle . ,


F4 ,

--
. -

- - -- - - - - - - - - - -- 2 95 - -- - -- - - - - - -- - -
Project Properties Project, - m ,

. , Standard ,
. ActiveX ActiveX
DLL, m, 13.2.
Name , InsIancing

, .
.

1 - Private defaulf () . /
. (component).
2 - PublicNofCreatable / " component
( ) -
. GreateObject New.
3 - SingleUse / ", ooou , c ompnent
. AetioX D.

4 GlobalSingleuse Singleuse,
. ActiveX DLL.
5 MultiUse . component
Vy n .

6 - GlobalMultiUse MultiUse.
.

component
( ), New
CreateObject, :

Dim v a r iable As Ne w Cl a s s l

Se t var i ab le Cr eat e Object ("MyProject.Clas sl" )


Public declaration class modUe , :

Pub l i c Name As String


Pub l ic Balan c e As Double

, :

Cla s s l . Name

Class1 .
Private

--
(property procedures). m -

- -- - - - - - -- - - - - - 296
read -only , standard modules
. , , module
. , Balance :
Priv at e dbBal anc e As Double

Public Prope rty Get Bal ance { ) As Doubl e


Balance = db8alance
End Prope rty

Public Prope rt y Let Balance (ByVa l db lNewBa l ance As Double)


dbBbalance = dbl NewBa l ance
End Propert y

Class1.Balance ,
Property Get, Balance Property Let.
, Proe rty 8et .

Private Dept As De partrne nt

Public Pr o pe r t y Let Parent() As Department


Se t Parent = Dept
End Prope rt y

~o

, Public
, :

Publ ic Sub Cre at e ( )

End Sub

Class l .C reate

Visual Basic 5.0 Friend.


Friend,
, modules .
, :

Friend Prope rt y Let Balanc e (dbl Ne wBalance As Double)


dblBalance = dblNewBalanc e
End r ope r t

["

Visual Basic 5.0 , ,


. .

--
2 97 - -- - - - -- - - - -- - -
Initialize :

Private Sub Cl as s -Ini t i al i ze ( )

End Sub

Class1, New.
Terninate, :

Pr ivate Sub Clas&-Terminate( )

End Sub

Class. :

Set Class_va riable = Nothing

( ; ) ,
. Events.Vbp
. Widget.
, LongTask. PercentOone,
Event .
RaiseEvent . m ,
, rue,
LangTask. :

Opt i o n Expl ic it
, O~6
Pu b l i c Ev ent Pe rce n t Done t ByVal Percent As 5 ing 1 e . By Re f Cancel As Bo o l e a n )

Publ ic Sub LongTas k(ByVal Duration As 5ing1e , ByVal Minimumlnterval As


S ingle}
Dim sngThreshold As 5i ng 1e
Dim s ngStart As 5ing1e
Dirn blnCance l As Boolean
, Timer 10 1

\ '
sngSt a rt = Time r
sngThreshold = Mini mumlnterva l
00 Whi l e Ti mer < ( s ng St a r t + Duration )
I f Time r > (s ngSt a r t + s ngThr e s ho ld) Then
PercentD one
Rai seEvent PercentDone ( _
sngThreshold / Durat ion, blnCanc el )
1 1

If blnCancel Then Exit Sub


sngThreshold = s ngThreshold + Min imum lnteral

End If
Lo op

--
End Sub

2 98 - - - - - - -- - - - - -- -
. ,
WithEvents New,
Dim. code editor
mWidget, PercentDone,
, .
Widget,
New, , commandbultons, label
gressbar control ( 13.3.). progressbar
control label. .
PercentDone:

Option Ex p l i cit

, Wi dget
Pr i vate WithEv e nt s mWidge t As Widget
Private mbl nCa ncel As Boolean

Priva te Sub Forrn-Lo ad{ )


Set mWi dget = New Widget
End Sub

Privat e Sub Form-Unload ( C ac el As Integer )


Set rnWidget = No t hing
End Sub

P rivat e Sub Commandl_C l ick()


mblnCance l = Fa l se
l blPerc entDone .Ca pt ion = "0 %"
lblPe r c entDone .Re fresh

Cal l mWidget . Long Task(1 4 . 4 , 0 .66 )


If No t mblnCancel Then
l blPe r c entDone.C a pti o n = 100
End I f

End Sub

Pr ivate Sub Co mmand2 _ Cl i c k()


mbl nCa n ce l = True
End Su b

K ~K v ~ i l 6
.

P riat e Sub mWid g et-Pe rcentDone (ByVa l Pe rcent As Si ng l e, Cancel As Bool e an)
lblPerc entDone. Ca pt ion = CI nt( l OO * Perce nt ) & ~ %"

ProgressBa rl. Value = CI nt (lOO * Percent)

Do Ev e nt s
If mbl nCa n c e l Then Cancel True
En d Sub

--
2 99 - - -- - - - - - - - - - - - -
iiii Form1 l00

C"n:;el

46%

. 13.3. .

. ,
ReDim,
. ,
,
ReDim
4
, . :

Add - .

Count - .

II_m - a .

D_I_I_ - .

Add :

ob j e ct.Add ( itern, ke y , b efore , a f ter)

ilem , key [
, before after
.
, Add, Inst
( Class1 ) MyCiasses:
Private Sub For.m-Lo ad ()
Dim MyC la s s e s As New Col l ect io n ' ~oo ~ .

Dim Num As Integer


Dim Msg As St ri ng
Dim TheName , MyObject, Name Li s t

Di m Ins t As New Classl ' Classl .


Num =: Num + 1
Msg = ~~ ~ ~ o ~~K o . " & vbCr
& ~ ~ Cancel YlQ . "

--
TheN ame = InputBo x(M sg, "Name the Co l lect ion Items")

30 0
I nst . I nstanceName = Th eName ' l l l

, l , l
, .

If Inst.lns t anc eN ame <> ~" Then


MyCl asse s . Add Itern: = Ins t , Key : = CSt r ( Num)
End If
, . a .

Set Inst = No thing


Lo op Unt i l TheName =

Fo r Each MyObjec t MyClasses ' 10 i .

NarneList = NameList & MyOb ject. Ins tance Name & vbC r
Next MyOb jec t

, Kal lQ . i .

Ms g Box NameLi s t, , ' s t a c e Name s MyC l a s s e s Col lect ion"

, l l l

Fo r Num = 1 MyClasse s.Count


MyCl a sses .Rernove 1
Next Nurn
End Sub

Item ,
, ..:

Se t Obj = colObj . l terns (5)

key Add.
Set Obj = colOb j. l tem s (~Demo" )

(ob)ect ne r .rc n )

. .
business,
, Employee, .
, business decla-
ratIon :

Pr ivat e colEmpl o y e e s As New Co l le c t i o n

Employee
. name salary.
, business, AddEmployee,
Employee :

Pub lic Function AddEmpl oyee(ByVal name As String, ByVal salary As Lo ng)
As Employ e e

--
Dim e mpNew As New Employ e e

3 01
St at i c intEmpNum As I nt e g er
intEmpNum = intEmpNum + 1
With empNew
. = ' & Fornat$ (intEmpNum, ")

. name = name
. s a l a ry = salar y
End With
co l Employe es . Add empNew , empNew .

Se t AddEmploy e e = e mpNew
End Function

, business,
:

Dim sbMa i n As New bu sine s s

AddEmployee, .

oim emp As Employ e e


Set emp = s bMain. AddEmployee (T e xtl , Text2 )

(polymorphism) VK O o
. Vlsual Basic 5.0, vo Implements, '
, .
. ,
. Animal ' :

Public Sub Moe (ByVal Oistance As Double )

End Sub

Public Sub Bite(ByVal What As Object)

End Sub

, . abstract class
.
monkey declaration :

Implements animal

monkey " " (interface)


, animal. Codeeditor, Object ,
animal , , (procedure)
Animal. "
" , 13.4.

--
3 02 - - - - - -- - - - - -- - - -
H.1tf!!i* , !,!$ _'r:1I
[ iml J I (. J
Opt io n E>lp li e i t
Move
Il'I1p~~_e rre: n.~ ~_.~ i rnal

Privat", 3wJ ",n Jma 1_ Bi t",(8yV,, 1 OI ha t


ffl'lq Bo x " 5 \>:
" ", CbJ",ct )
Typ erTIE; (I< hat )

-
_~lI '>

Privat '" '> a n i ma l _ Hove ( By Va 1 IH "H:.. ne e , Doub1e)


It3 QBox '' ~ KL 8 K ((

End S ub

-
2 : ~ ~

. 13.4. " " .

, flea ( ), i
Animal, :

rmplement s a n i mal
Priv at e Sub animaL-B ite(ByVal What As Object)
MsgBox ~O ~ & Ty peName (What )
En d Sub

Pr i v ate Sub a n i maL-Mov e ( ByVa l Distance As Doub l e )


MsgBo x ~ O vn "
End Sub

monkey flea.
anim, 5et, i (reference) flea,
Bite flea, [ monkey, i
Bite.

Dim f l As fle a
Dim mk As monkey
Dim anim As animal

Set f l New flea


Set mk New monkey

Set an i m ~ f1 ' f 1ea


Ca l l anim.Bite(mk) ' a Bi ke flea.

Set anim = mk
Call anim.B ite(fl ) 'a Bike monkey.

, anim i i i
animal. Bite early bound i
anim, i i (compile time)
i anim Bite.
i , i .
:

--
3 03 - - - - - - - - - - - - - -
Public Sub GetFd Va l Critter As Object, ByVa l Fo od As Object)
Dim dblDistance As Double

Critter.MovedblDistance Late bound


Cr itter.Bite Food Late bo und
End Sub

Move 8 ~e late bound Ctt er


ObjecI. , , Visual 8asic
Crilter.
,
. CrItter Animal, Move 8ite
early bound.

wizards Visual 8asic 5.0 Class 8uilder


, l . ,
,
.

.t":ttt~ !l
,~ <.. - "

~I ;"I ~ I ~ t l ll"
I ~~:
~ ~~
dassL
2.
.......,..
froperties I ~ E~ s ~
,.....
.

--
_"IS

. 13.5. .

AutOJJJl1ttoTI Servers
Visual 8asic
L AutomaUon.
Visual 8asic L AutomatIon se rer.
L Automation serers: in-process out-ot-process.
(DLL) (code segment),
(data segment) . o t-of- p rocess

in-process se re rs .
L Automation serer ,
Project Properties Project (Project Type) ActiveX
ActIveX DLL. ot-of-process in-process serers .

--
ate , .

- - - - -- - - - - -- - - - 304

Projed Iiet
Corte:d:JP:

'


r ~~ per Qt>jed
r. n.Md i'""""""3 t:tYeads

...
. 13.6. l Automation Serer .

Visual Basic, L Automation


Serer, CreateObject GetObject. :
CreateOb ject ( c lass )

class "appname.objecttype", appname


, objecttype .
, worksheet Excel
.

Dim x l She e t As Ob ject


Set x l She e t = C reateOb jec t( ~E xc el. Sheet " )

x l Sheet. Vi s i b l e = Tr ue
She e t . Rang e ~ " ) .Vaue = ~ T e st"

xl Sheet . Range ( "A2 ", "C3" ). Va l u e = 500

;filil9

~!"~ Releence;: '=' ::i=


SU 8MC F ~ """, -
Vsu 8.asic obie .an:l ~
1040"""" Corro:n Di.q ;trd
St.idon obbed l>ioIt CoI
r.t"""""" Rch Je><Ibox Col
. :: . *'"b. $ . "Iffl:
MooJoII D4I<1I 80rd Lt CoIO
J ~
1'.- 1
- D"'" l3ou'd 6id \.:.,
S~OU:~
G r.to<c> DALJ 3.0DI;jecLb.,
DS~OLET~
"""
.!J
-""= 1
Dlotcoo</l;DAO 2. 50h0ct Lb...,.
OIoIco'tsulB<1IS:.O~4';"'. ~

. ~~~-

Ioticcdl ......n:bwsComJn C::fi


,~-

"=
Dc \\oIIN.OOWS\5Y5TEM \/NCL32.1X<1I
""""" ........
"'-'"

--
. 13.7. Reierences.

3 05 - - -- - - - - - - - - - -

, Microsoft Excel object library, , Project ,
References,
objecf lbraes ( 13.7.).
, Browse Olb Tlb.
(object lbra es) Visual Basic .
References,
Object, , .
. , , Visual
Basic . , .
, , , X15en32.01b
References, :

Dim x lShe e t As Exce l.Works h e et

Object Browser Ecel


7.0 XI5en32.0Ib.
, workseets
' .

Dim As Ex ce l .App l i c a t i o n
Dim mySh e e t As Work s he e t
Se t = Crea t eOb jec t(~Ex ce l. Appl i c at i o n W)

Wit h

workb o o ks. Add


workbo o ks. Add
Se t mySheet = . wo r kb o o k s( 2) . Wo r ks he e t s ( 3)
Vi sib l e = Tru e
End With
myShe et . Se l ect
my Sheet . Ra ng e ( "Al :C3 " ) . Va l u e "2 00"
. Qu i t
Se t = Nothing

ui Excel. , ,
.
, For Each... Nexl,
worksheets Excel:
Dim As Ex ce l.Application

Dim rny She et As Wo rk s heet

Set = Cr eateOb ject ( "Exc e l . Application" )


With
. wor kbooks . Add
For Ea ch mySh e e t . Wo r ks he e t s
MsgB ox myS hee t . Name
MsgB ox my She et .Rang e ( "Al" ).Value
MsgBox myShe et . Range (U Al n ).Font . Size

- - - - - - - - -- - - - - - -
--
306
Next mySheet
End With

xl.Quit
Set xl = Nothing

nwyj 'IIord
Micrasaft Word,
VBA, Word 95 Basic, WordBasic.
(document) Word OLE
Automation , ' ,
, , . .
FileNewDefaull, defaun tem-
plate NormaI.Dot). FileNew, ,
(
template. Word ( Excel)
, CreateObject. AppShow
. :

Dim wd As Object

Se t wd = C r eat eObject ( ~ wo rd. ba s icH )

wd.F i l eNewDefaul t
H
wd. File New "c : \ me r i\ he l p. dot
wd.AppShow

FiIeOpen .
, error handler ,
.

Er ro r GoTo Wo rdError
Dim wd As Ob ject

Set wd = Cre at eOb j e c t ( "wor d. ba s i c H )

wd.F i leOpen "c : \ Docs \ he l p. doc H

wd.AppShow
Exit Sub
Wo rdEr r o r:
Ms gBox Er r.Number & " " & Err . De scription

'
Insert. ,
, FileSaveAs.
Dim wd As Obj ect
Dim My Te xt As String

Se t wd = C rea t eOb jec t (" wo rd. ba s i c ~ )

Wi t h wd
. FileNewDefau lt

--
30 7
AppShow
MyText " Word" & vbC rLf
MyTe xt = MyText + " "

'

Insert MyTex t
'

Sta r tOfLine
'

.SelectCurSentence
MyText = " v "

I nsert MyText

'


I nsertP ara

Le f t Pa r a
I n s e r t ""


Bo ld
.
Fi l e Sav e As Name:="NewDocument"
End With

Word ; ,
, '
Toolbars. CounIToolbars , ToolbarName$
Toolbar, ToolbarSlale .
Dim wd As Object
Dim Too lbarArray() As Var iant
Dim Name As String, i As Integer

Set wd = CreateOb ject ( "word.basic")


wi t h wd
For i = 1 .CountToo lbars
ReDim Pres erve ToolbarAr ray(1 , i)
Name = [To o l ba rName $] ( i)
Too lbarArray ( O, i ) Name
ToolbarArray (1 , i ) = Str$ ( .ToolbarState(Name
Ne xt i

For i = 1 .CountToolbars
MsgBo x ToolbarArray(O , i), 1 6, ToolbarArray(l , i)
Ne xt
End With


Word, CurValues.
)
. , , i ToolsWordCount
, .

--
:

3 08
Error Go To WordError
Dim wd As Obj e c t , DialogObj As Obj e ct

Set wd = CreateObject("word.basic")
With wd
. File Op e n "c : \ Do c s\ he l p . d o c "
. AppShow
Set Di a l o g Ob j = .CurValues . Too lsWordCo unt
MsgBo x " : " & DialogObj .Pages & vbC r Lf
+ " . : " + Di al ogOb j . Pa r a g r ap h s + vhCrLf
+ " : " + Dia l o gObj . Lines + vbC rL f _
+ "~ : " + Dia l ogObj . Words + vbCrLf
+ ".: " + Di a l o g Ob j . Ch a r a ct e r s
End with
Exit Sub
WordError:
MsgBox Er r .Number & " " & Err.Descript i on

ToolsWordCount WordBasic :
ToolsWordCount [. Co untFo otnot e s = number ] [ , . Pa g e s = t e xt] [, . Wo r d s
text] [, . Cha r a c t e r s = text ] [ , .Paragraphs = text ] [, .Lines = text]


tab Genera/ OptiGns Tools Ward.
.

Dim wd As Obj e c t , Di a l o gOb j As Objec t

Set wd = CreateObject("word.basic")
with wd
. Fi leNewDefau lt

Set DialogObj = Cu rValues. To o lsOpti ons General


Se lect Ca s e Dia logOb j.BlueScreen
Ca s e
. Too lsOptionsGeneral 1
Ca s e 1
. Tool sOptionsGe neral

End Select
End Wi th

Word, :

wd. AppClose
Set wd = Not h i ng

, macros,
ToolsMacro. Visual Basic macros
, Word [ . ,
' macro. [ macro:

--
3 09
Dim wd As Objec t

Set wd = C re ateObj ect (~ wo rd. ba sic " )

W'ith wd
. Fi leOpen ~c : \ do c s\Ga i a . Do c "
. AppActiv ate ~Micros o ft W'o r d "
. ToolsMacro Name :="MyMacro ", Run: =True
End W'ith

- ni

SIack

Stack (stack)
LIFO. Push ,
, . Count
, , , Item
. , :

Di m Stck As New Stack

Stck . Push " "


St c k. Push " "
Stc k.Pu s h "Tree "

MsgBox Stck.Cou nt
MsgBox Stc k. ltem ( l) & " " & Stck.ltem( 2) & " " & Stck. ltem(3 )
MsgBox Stck.Pop
Ms g Bo x Stck. Pop
Ms g Bo x Stck.Pop

x ~ K~K :

De fLng -
Pri v a t e nStack As New Col l e c t ion

Pub l ic Fun ction Item(itm As Long) As Va r i a nt


If itm <= Or i t m> Count Then Exit Funct ion
Ite m = n St a c k.l t e m( i t m)
End Funct ion

Pub l ic Sub Push (vArg As Va r i ant )


nStack.Add vA r g
End Sub

Pub li c Function ( ) As Va r iant


With nStac k
I f . Co unt Then
= nStack ( .Count)

--
3 10
Remove ( . Count)
End If
End With
End Function

Prope rty Get Count ( ) As Long


Co unt = nStac k.Count
End Pr o perty

Spell Checker Word



Word Spell Ghecker. "
Visual BasIc, . ,
, text box control
ttS pelling . command btton controI tet box.
, Spell Ghecker ToolsSpelling.
WordBasic , Error.
' , tet box control.

Priv ate Sub Cornmandl_Click ( )


Dim wd As Object

Set wd = C re at eObj e c t ( ~ wo rd. ba s i c " )

With wd
F i l e Ne wDe f a u lt
. I n s e r t txtSpell ing.Text
Error Re sume Next

To o lsSpell i ng
EditSelectAl l
.CharLeft Count:=l . Select:=l
txtSpe l ling. Text = [ Se l e c tio n $] ( )
. FileClose Sa ve: =2 ' o K ~
End With
End Sub

InOJrnet Explorer !:


Internet Explorer ,
Automation Server, . ',
Explorer Visual BasIc, Shell,
References Tools SHOOGVW. OLL.
Internet Explorer .
,
buttons
OecIaration .
Priv a te As Ne w I nt erne t Exp l orer

GoBack, Goforward, Refresh, Navigate,


Explorer (URL) .

--
311
.. Control Dem: I!!lIiJ 13

G~At:

EndDemo

. 13.8. .

. Visible
Explorer:
Option Expli c i t
Privat e As New Internet Exp lorer

Private Sub c mdBro wse r_Clic k ( I ndex As Int e g er)


Local Error Go To BadcmdBrowser:

Se lect Case Index


Ca s e o~
IE . Vi s i b l e = Tr u e
Ca s e 1 ' ~
I E. Vi s i b l e = False
Ca s e 2 ' URL
IE.Navigate Te x t l . Te xt
Case 3 ' u rl
Te xt l.Text = I E. Lo cat i onURL
Cas e 4 ' back
I E.GoBack
Cas e 5 ' f orwa r d
I E.GoForward
Cas e 6 're f r e s h
I E. Re f r e s h
Ca s e 7 'T ~

Unload Me
End Select

Private Sub Fo rm-Un l o a d ( Ca n c e l As Integer}


Error Resume Next

IE.Quit
Set Nothing
End Sub

; Intemet Explorer
control.
SHDOCVW.DLL, ,
WebBrowser control, browsing Visual Basic.
, Browse, GoBack, GoForward,
GoHome, GoSearch, NavIgate, , Refresh Stop, , OnBeginNavigaIe,
OnCommandStateChange, OnOownloadBegin, OnOownloadComplete, OnNavigate, OnNewWindow,

--
3 12
OnProgress, , OS tatusTextCha ge .

tabIe ' Excel


,
database table Ec el spreadsheet, L auto-
mation. tab I 2eI .vb p :

Pr ivate Sub Cornmandl_Click()


Dim i As I n t e g e r, j As Integer
\ Record
Dim rCount As Long
, OLE automation object
Dim As Object
, Database object
Dim db As Database
\ Snapshot y~ records
Dim 5 As Recordset
Dim mySheet As Variat

Screen.MausePointer = 11
La b el l . Ca p t i o n = "Creating Excel Object"
Labe ll.Refresh

Set = CreateObject ( "Excel.Application" )


With

workbooks . Add
workbooks . Add
Set mySheet = . wo r kb o o k s ( 2 ) . Wo r k s h e e t s ( 3 )
Visible = Tr u e
End With
mySheet.Select
La be l l . Capt ion "Opening the database"
Lahell . Refresh

Set db = Workspaces(O ).OpenDatahas e(RBIBLIO.MDB")


, ~ FieId names Co lumn names:
Labell.Capt ion = RCr e a ti n g SnapShot"
Labell .Refresh
Set Sn = db.OpenRecordset (RTitles", dbOpenSnapshot)
If Sn.RecordCount > Then
, ~ fields s p r e a d s h e e t
Labe11.Caption = RAdding field names to Spreadsheet"
Labell.Refresh
For i = Sn.Fields.Count - 1
. cel ls(1, i + 1) . VaIue = Sn(i). Name
Next
, K~ Update record K~
, ll record
Sn.MoveLast
rCount = Sn .RecordCount
Sn.MoveFirst: i =
Do While Not Sn . EOF

--
31 3
Labe11.Caption = ~Record : & Str ( i + 1 ) & ~ of" & Str (rCount )
Labell.Refresh
For j = Sn. Fields. Count - 1
\ o~ fie ld s p reads heet
If Sn( j) .Type < 11 Then
, cel ls (i + 2 , j + 1). Value Sn (j )
Else
. c ells( i + 2 , j + 1) . Va I ue ~ Memo o r Bi nary Da t a "

End I f
Next j
Sn.MoveNext
i = i + 1
Loop
\ e xc e l obje ct - ao K ~ Exc e l a
Label l .Caption = ~Quitting Excel "
LabeIl .Refresh
xl. AppI i c a t i on. Quit
EI s e
, .

End If
Label l . Caption = ~ C l e an i ng
LabeIl.Refresh
Set Nothing AoK ~ object variable.
Set Sn = Nothing AOKV~ snapshot ob j ect.
Se t db = Nothing A oKV~ da tabase object .
Scre en.Mou s eP ointer =
Label1 . Ca ption = "Ready"
Labell. Re fresh
End Sub

MDI
, MDI,
.1 , . . ,
13.9. CMRU
dnte.
Registry
p~ .

b! 4

--
. 13.9. Mdinote.

3 14
.
' separator mnuSeparator ExiI
mnuFileMRU, Index Visible False.

Publ i c m-o b jMRU As CMRU

Load :

Set rn-objMRU = Ne w CMRU


m-ob jMRU.OpenMRU mnuF i leMRU

, ,

rn-objMRU.UpdateMRU f i l e name, mnuFi l e MRU

UnLoad, Registry.
m-ob j MRU. Cl o s e MRU mnuFileMRU

Menu item mnuFileMRU


GetFileName , ' :
Priv at e Sub mnuF i leMRU_ Click(Index As Integ e r}
Dim sFileName As String
s Fi l e Name = m-ob j MRU.Ge t Fi l e Name( In de x )

End Sub

. CMRU,
:

Opt i on Explicit
Co n st MAX-LEN = 32
Privat e mLiArrayNum As I nt e g e r
Private mLiMaxAr r ay As Integer
Pr i v at e m-sFil e Array() As String

, . ~ K

Cons t APPLNAME = ~ App l i c a t io n Name H


n

\ a
, Re gi st r y .
Public Sub OpenMRU(mnuAr ray As Var iant )
Di m vaMRU As Variant , i As I nt e ge r
Dim s F il eName As St r i ng

vaMRU = GetAl lSett i ngs (APPLNAME, ~MH" )


If Not I s Empt y ( v aMRU ) Then
Fo r i = LBo und (vaMRU, 1) UBound(vaMRU, 1)
sFi 1eName = vaMRU (i , 1)

--
3 15
If Len(sFi leName) Then
If rnLiArrayNum Then
Loa d mnuArraY(ffi-iArrayNum)
End If
ffi-sFileArray(rnLiArrayNum) = sF ileName
mnuArraY(ffi-iArrayNum) . Cap tio n = FormatName(sFileName)
mnuArray( rnLiArrayNum).Vis ible = True
If ffi-iArrayNum < m-iMa xAr r a y Then
ffi-iArrayNum = rnLiArra yNum + 1
Else
Exit For
End If
End If
Next
End I f
If rnLiArrayNum Then
Load mnuArraY(ffi-iArrayNum )
mnuArray(rnLiArrayNum) .Caption
mnuArray(rnLiArrayNum ) . Visible True
End I f
End Sub
, Registry .
Public Sub CloseMRU(mnuFileArray As Variant)
Dim i As I nt e g e r
For i = rnLiArrayNum - 1
SaveSe t t ing APPLNAME, "MRU", " File " & i + 1, ffi-s FileArray( i)
Ne xt
End Sub
, vn
\ .
Pub lic Sub UpdateMRU( rsF ileName As String, mnuF ileArray As Variant)
Dim i As I nt e g e r , J As Integer
I f Len (rsFi1 e Na me ) = The n Ex i t Sub
Fo r i = rnLiArrayNum - 1
If LCase(ffi-sFileArray(i)) = LCa s e ( r s Fi1e Name ) Th e n
For J = i 1 Step - 1
illLSF i1eArray( J) = ill-sF ile Ar r a y (J - 1 )
rnnuFi l e Ar r a y (J ). Cap t ion = mnuFileArray(J - 1) .Ca ption
Next
illLSF i l eArray ( O) = rsF i leName
mnuFi leArray( O).Capt i on = Forma t Name ( r s Fi l e Name)
Ex i t Sub
End If
Ne xt
If ffi-iArrayNum < ffi-i Ma xAr r ay Then
For i = ffi-iArr ayNum 1 Step - 1
ffi-sF i l e Ar r a y ( i ) = ffi-sFi leArray( i - 1 )
mnuFi l e Arra y ( i ).Ca ption = mnuFileArray( i - 1 ). Cap t i on

--
3 16
Next
rn-sF ileArra y( O) = r s F i l e Name
mnuFile Ar ray( O) . Ca ption = Fo rma t Name ( r s FileName )
mnu Fi l e Array( O).Visible = True
rn-iArra y Num = rn-iArrayNum + 1
Lo a d mnuFi leAr r a y(rn-iAr rayNum)
mnu Fi l eA r ray (rn-iAr r a yNum ).Caption
mnuFileAr r a y( rn-iAr ray Num). Vi s i b le Tr u e
Else
For i = rn-iArrayNum ~ 1 1 St ep - 1
mnuFileArray(i) .Caption = mnuFile Ar r a y (i - 1 ) .Ca p t io n
rn-sF ileAr ray (i ) = rn-sFil eArray (i - 1)
Next
m-s FileArray (O ) = r sFileName
mnu FileArray( O) .Caption = Forma t Name ( r s F i l e Na me )
End I f
En d Sub

\ E ~ ~
\ ri lndex.
Pu bli c Function GetFil eNam e ( r i l ndex As Intege r ) As String
Ge t FileName = ffi-2F i leArray (ri lndex)
En d Fun cti on

\ o oo ~
\ ~ KnO~ O .
Priv ate Function FormatName (rsFi l e Name) As String
Dirn sTemp As St rin g , iStart As Int e g er, i Found As l n t e g e r

If Le n(rsFi leName) <= MAX-LEN Then


Fo rmat Na me = rsFi leName
Else
sTemp = r s Fi l e Name
iStart InStr (sTe mp. ~ \") + 1
iStart InSt r (iStart , sTemp , ~ \") + 1
iFound l n St r (iStart, s Te mp, " \ .. )
00
I f iFound = Then Ex i t
s Te mp = Left $ sem, iS t a r t - 1 ) & " .. . .. & Mid$ (sTemp , iF o u nd)
iFo u nd = InStr (iStart + 4, sTemp. " \ .. )
Loop Whil e Len ( s Temp ) > MAX-LEN
FormatName = sTemp
End If
En d Function

\ ~ o X ~K ~ ~
Pri v a t e Su b Class_I nitializ e( )
m-iArr a y Num =
L...iMaxArray = 5
Reoim ffi-SFil eArra y( O 4 )
End Sub

--
3 17

1. vr; r vr; -
rrK vr.

2. Visua/ asc;
3. vr /mp/ements.
4. Severs; ;

1. TgFile, .
( 30)
. - Ei sl, Open, FreeFile
, .

2. , TgSlring,
. .

3. TgComDialog,
ShowColor, ShowOpen, ShowSave, ShowPrinler, Show Fonl ShowHelp CommonDialog clI'
: , CommonDialog
Inilialize .

4. Zoo.Vbp, ,
Animal "" .

- - -- - - - - -- - - -- -
--
31.

- --------
'
~/ 'lII "H-~ ~'

.111
, !f-
ActtveX ctr's

Visual Basic 1,0, '91 ,


VBX, ,
, controls, control , .
, controls, L (Object Linking
and Embedding), OCXs, 32-bi!. Internet,
Web, , . ActiveX
Microsoft 1996
L controls Internet.
" " controls Web, ,
ActiveX controls, " " ,
,
. , ActiveX controls Internet,
,
, ActiveX controls, controls ,
Visual C+ +, control Microsoft
Foundation Classes, L ( )
, control MFC40,OLL ( 4,0), MSVCRT.DLL
( Visual C+ + Run Time) OLEPr032, DLL L. Visual Basic 5,0
controls,
Visual Basic 5,0, VBCCE (Visual Basic Control Creation Edition),
ActiveX controls p-code ,

n Ac;tveX cotrl

Visual Basic 5,0 ActiveX controls,


, Exlender (standard) ,
controls ,

Ambient. , ActiveX
control. control controls (composite con-
trol), ' (subclass) , ,

--
control ,

3 19 - -- - - - - - - - - - - - -
control spinner control.
. New Project File,
.

b s,.. :::::<:J
~
"""""XD
lIi ~
.-(-
"
Wi>>rd
ou
~
'I!J I pt "'" \'8 fuerons.
~ co ...
~
- ~- ~
~
A<I~. ""


. 14. 1. .


ACtiV3X control .
,
UserConIrol1,
control. control
xt box txtSpinnerValue (vertical scroll-
bar), vsSpinner. controls UserControl1.

~':~'";"'P'"'.'~
. I__ ~
. 14.2. ActiveXcontrol, controls .

Value Max scrollbar control 100.


, CodeWindow Change control, :
t xt Sp inne rVa lu e = 1 0 0 - vsSpinner. Va l ue

. ';,;;g,.'.l.\!l.Iii8!fti'4 _ !!'
l~sSpinn.,,- :J jCh. nge :J
P ,, ~ .. t ~ ,~
U" "rC Dntr o l Initia li z .. ( )
- ..:
, , ,~

" " .. ,~
v"Sp inn .. ... C hang .. ( ~

GW"I!.iJG-"tiPJ,
f '''.j@
,, ,~

!.
,.j-ill ~

--
. 14.3. Code Window Change.

3 20
, UserControl1. ( 14.4.)
Toolbox control ( )
UsetControl1.
control'

I ~ ;'~
abi " -.J
r- IIJ
~ .!HJ ;

. 14.4. oo lbox controI.

Visual Basic 5.0 , , group project,


projects. , File Add Project...
Standard . project,
Project2 ( praject Project1j, Project Explorer,
projects group.

Q1!Ji,I"'I',III.Oell.iii..
tii ~je:;, . ~
:~ ~ :~J~ ~=C:S1)
jjf L1ie::o-I;r"n (U>er<:ontolI
! ~ Ptoj"ctz (P,oje<:tZ)
i:: ~_~ Fo<m;
I:1 @, i1@ !i1

1-'.1

. 14.5. Project Explorer. .


Form1
project Toolbox control UserControl1
. F5, ,
ActiveX control .

... Project2 - Form1 (FO r~ ) I'!J

", '

--
. 14.6. projecl, ActiveX cotrol UserControI1 .

32 1
control .ctl, project
.vbp, , , group projects .vbg.

Activex' IJjterffce coJjtro/ 'Ilizfrd

ActiveX control , .
. ActiveX Inlerlace Conlrol Wizard
Add-Ins. 6.10., default ,
ForeColor, BackColor, Click ..

BeIw ;s" ist '* Prerty,~, l"ldEvenI; MI"!'JeS tht \'O'J


it -. \ISoei1 YJ' ,onl.

Theonest!at hrv~ been prc-seIe<:t..de st>dd Prert'y,


MetI"OO, ".-.j Ee<t wnes thatrnost rtfols so<t .
CkkNext todd you-"""Pr<crtoo>,~, od Eve!J;:S,

Ao: "" r ,oI Pr oer ty B4ek( oIar Pr o e< ty


AIio;roent Pr oe<ty """". Pr Oet Y
A pe lC "
Asyn<RNd
f'foe ly
Mei:hod
eorokrstyle
,-
P< o e< t

,~"
",.yn<RudC omI ete
AuoR. e<Ir _
C~ IA.yncRed
Event
PrOefly
Med>od
"""'
En~d
,~
"- "
"' oe<y

~=Y ~
c~tyCh blqe" Mel:hod ForeCo/Qr
a...,. ,-
"""""

. 14.7. ActiveX Interface Control Wizard.

, Net,
, . ( 14.8.)
.
InitValue, tet box scrollbar ActiveX control.

Add Custom Member

<
e- -

@\,-

. 14.8. .

Finish, Wizard ,
.
control, m m

m_, m_BackColor, m_Enabled . .

--
standard , Ciick, DbClick ..

3 22 - - - - - - - - - - - -- - -
Event. InilProperties con-
Irol' ReadProperties cantroI
, controI,
ReadProperly TOU u PropBag, :
Pr i v at e Sub UserCont r o l-ReadProp ertie s(PropBag As Prope r t yBag )
Er ro r Re s ume Ne xt

' ~ ~ ~ Masked.

Masked = Pro pBag.ReadP rope rty(~Mas kedw , Fal s e )


. l.1. . . .
End Sub

ReadProperty ,
, default .
contraI ,
WrileProperties, Wr~ePropey PrapBag.
Pr ivate Sub Use rCont roL-Write Propert ies (PropBag As Prope rtyBag )
Call P ropBa9 . Wr i t eP roperty ( ~ B ac kCo lorn r mLBa ckColo r , rn-de f -BackCo lo r )
. . l. 1. . . .
End Sub

, WrilePrOperty
, , defau ~
.
, cantral.
.
PropertyChanged, Let,
BackColor control:
Pub l ic p rop e rty Let Ba c kCo l o r (B yVa l Ne w-BackCo lor As Long )
mLBackColo r = Ne w-BackColo r
Pro pertyChan ged ~ B ackColorw

End Pr ope r t y

Get ,
u:

Publi c Prope rty Get Ba c kColor{} As Long


BackColor = m-BackColor
End P roperty

,
control , design:

Initialize control .
In ~Propeti e s control ! / . n
Extender Ambient.
Resize. Paint control control

--
( p.In!).

3 23
F5 , control
design run time.
:

WriteProper1ies control / design,


.frm .

Terminate control design.


Initialize control time
.

ReadProperties contro! vo .f
. Extender Ambient.
Resize, Paint control control
( Pain!).

, control WritePropertIes Terminate.


controI (compilation ), Visual Basic
( ) control .
Initialize, ReadProperties WriteProperties.
controI ( ; Visual Basic),
, control Initialize, ReadProperties Resize.
, control Terminate.
Visual Basic, L design. ,
control L, ,
Initialize, InitProperties, Resize Paint browser.
control, [
ScaleWidth ScaleHeight control.
control. , Resize ,
control.
, control,
shpBack. cantrol label control ,
[ . , Resize :

Private Sub Us e r Co n t r o l-Re s i z e ( )


, Shape control
, ShapeLabel control
shpBack. Move , . ScaleWidth, Sc a l e He i g ht
, 6 Label
blCapt ion. Move , ( Sc a l e He i g ht - lblCaption. Height) / 2, ScaleWidth
End Sub

c ontrl controls
BackColor, background controls
;

Pub l i c Prop e rty Get BackCo lor () As OLE-COLOR


BackCo l o r = UserControl.BackColo r
End Property

-
.-
324 - - - - - - - - - - -- - - --
Pub l i c Property Let BackCo l or ( ByVa l NewColor As OLE-COLOR)
Dim o bj Ctl As Obj ect

Use r Co nt r ol . Ba ckC o l o r = NewColor


Fo r Each o bjCtl 1 Controls
1f (Ty pe Of objCt l I s OptionButton ) Or (Ty pe Of objCtl Is Che ckBox) _
Or ( Ty peOf objCtl Is Label ) Then
objCtl.BackColor = NewColor
End 1f
Next
PropertyChan ged ~ BackC olor "
End Prope r ty

OLE_COLOR ,
,
.
control s
MousePo[nter, control :

Pub lic Propert y Get Mous ePointer ( ) As Mous ePo int e rCon stant s
MousePointe r = UserControl .Mous ePoint e r
End Pr op ert y

Pub li c Property Let MousePointer (ByVal NewPo int e r As MousePointerConstants )


Us e rControl.Mou sePointer = Ne wPointe r
Prope rtyChanged ~MousePointer"
End Property

(Object >rerte 5 )

control
ActiveX control ,
. , LabelFont, labels
controls UserControl:
Public Property Get Labe!Font ( ) As Fo nt
Set LabelFont = UserControl .Font
End Proper ty

, Property Set V1Q obj ect propertie s.


Pub lic Property Set LabelFont{ByVal NewFont As Fo nt)
Set UserControl .Font = NewFont
Syn cL abe l Fon t s
Prope rtyChanged ~LabelFont"
End Property

P riate Sub SyncLabelFont s ()


Dim objCtl As Object
For Ea c h objCtl 1 Co nt r o l s
1f TypeOf ob jCtl Is Label Then

--
Set objCtl.Font = Use rCont rol.Font

3 2 5 - -- - - - - - - - - - - - - -
End If
Ne x t
End Sub

, , Font standard .
Private Sub UserContro l-1nitProperties()
SyncLabe lFonts
End Sub

Private Sub UserCont roL-ReadProperties(PropBag As VB.PropertyBag)


Erro r Resume Next

Set LabelFont = Pro pBag .ReadProperty(~ Lab elFont")


End Sub

Private Sub Us e r Co nt r o L-Wr i t e Pr o pe r t i e s ( Pr o p Ba g As VB.PropertyBag )


PropBag.WriteProperty ~LabelFont ", Labe l Font
End Sub

LabelFont, :

Private Sub CommandL-Cl ick ( )


You rContro ll .Labe lFont .Bo ld True
YourControll. Lab elFont.Name ~Courier"

End Sub

, controls
ActiveXcontrol . :

Pr o pe r t y Get Te xtl ( ) As Te xtBox


Set Textl = Textl
End Property

ETlJJ n~v

, FavorIteDinosaur,
.
' :

Public Enum DINOSAUR


dnoTyrannosaur
dnoVe lociraptor
dnoTrice ratops
End Enum

Private mdnoFavoriteDinosaur As DINOSAUR

Public Property Get Fav o r i teDi no s a u r ( ) As DINOSAUR


FavoriteDinosaur = mdnoFavoriteOinosau r
End Property

Public Property Le t FavoriteDinosaur(ByVal NewDino As DI NOSAUR

--
mdnoFavoriteDinosaur = NewDino

3 26
PropertyChanged ~FavoriteD inosaurH

End Property

FavorIteDinosaur dnaTyrannosaur, dnaVelociraptor


dnoTrIceratops control.

E xterder

control captIon,
control. :
Pri v a te Sub use rControl-Ini tProperties()
Capt i on = Extender. Name
End Sub

Extender Name, , Lett .. ,


control .
CaptIon, U serC ntr WriteProperties:

Pr i v a te Sub Use r Control-WritePropert ie s(PropBag As Prope rty Ba g )


Pr o pBa g .WriteP roperty ~Caption " . Capt ion, Ex te nd e r .Name
End Sub

Extender Cancel, DelaUt , Draglcon, Heighl, Width, Index,


Tablndex, TabStop, Tag, Visible WhatsThisHelplD. , Drag, Move,
SelFocus, ZOrder ShowWhatsThis. , DragDrop, DragOver,
GotFocus LoslFocus.

Arnbtert

control ' , contaIner


, ambient,
control contaIner. , ambient BackColor
control BackColor container.
ambient control .
Ambient UserMode,
control design (UserMode = False) Run time.
design control
(developer), time (user) .
(author) control. ForeColor,
BackColor, Font TextAlign.
,
control design, EdtAlDesgnTime
UserControl rue.

control, oval, Click

--
.

3 27 - -- - - - - - -------
declaration module control:
Opt ion Explic i t
, publ i c Click

Publ i c Event Cl ick ( )

, MouseUp UserControl :

Pr i vate Sub Us e rCo n t ro l-Mou s eUp ( Button As I nte g e r ,


Shi f t As Integer, As Single. As 5 1 0g1e )
If Point(X, ) = s hpBa c k. F i l lColo r Then
Ra iseEvent Cl ick
End If
End Sub


oval ( shape contol
control), Click RaiseEvent.

l1o~ IJjterJjet coJjtrols


ActiveX controls Visual Baslc 5.0 ""
(asynchronous downloading) , Picture,
bitmaps. Hyperlink UserControl,
lntemet Explorer ' URL history list.
HyperLlnk . NavigateTo
URL, :

Private Sub UserContro l-Click ( )


HyperLin k.NavigateTo "ht tp: / / www. mi c r o s o f t.com"
End Sub

GoBack GoForward
history Ilst:
Privat e Sub Us e rCont ro l-Cl i c k ( )
Error Re s ume Next
Hyperlink. GoForward
End Sub

control browser ( IntemetExplorer), AsyncRead


" " .
(background), .
,
control AsyncReadComplete.
, ActiveX control,
Plcture ,
PlctureFromURL,
bitmap, plcture box control
ActlveX control. pIcture box control
AutoSize.

--
, .

3 28

UserGontrol Name AsyncBi1map


Picture80x Name picBi1map
AutoSize True

i Picture control:
Pub l ic Prope rty Ge t Picture ( ) As Pict ur e
Set Pi ctu r e = picBitmap . Picture
End Pr op erty

Publ ic Pr o pe r ty Le t Pictur e ( ByVal NewPicture As Picture)


Se t p i c Bitmap.Picture = NewPi cture
Pr op e rt y Cha nged ~ Pi cture"
End Prope r t y

Publ i c Property Se t Picture ( ByVal NewPi cture As Pi c t u r e )


Set p icB i tmap.Picture = NewPi c t u r e
Prop e r t y Cha nged ~Pi c ture "
End Pr op e r t y

, ActiveX control picture pictureboxcon-


I. PictureFromURL, i private:
Opt i o n Explicit
Pr i v at e mst r Pi ctureFromURL As St ring

, , LoadFinished,
i .

Ev e nt LoadF i n i s he d (Ca nce l As Bo ol e a n)

, i Get Let:
Pub l ic Pr operty Get P i c tureFromURL() As St r i ng
Pi cture Fr omURL = mstrPictureFromURL
End Prope rty

Pub lic Pr ope rty Le t PictureF r omURL(ByVa l NewString As St ring )

mst r P i c t u r eF r omURL = NewSt r i ng


I f (Ambi e nt . Use r Mo de = True) And (NewStr ing <> ~ ") Then
, i ~ r un time Ka~ ,
, l ~K " l
AsyncRead NewString, vbAsyncTypeP icture , ~Pic tureF ro mURLH

End If
PropertyChanged ~ Pic tureFromURL"
End Pr o pe rt y

AsyncRead :

As yncRe a d Targe t , As y n c Type [, Property]

-
.-
329
Target
URL. AsyncType
po ov :

VbAsyncTypePicture Picture.
VbAsyncTypeFiIe Visual Basic.
, AVI .
VbSnCe ytea byte.

Property
" " . " "
AsyncReadComplete vo Select, :

Private Sub Us erCont ro l-Async ReadComplet e (As ync Prop As AsyncPr opert y )
Erro r Re s ume Ne x t
Dim Canc el As Boolean

Sel ect Case As y nc Prop.Prope r t yName


Ca s e UP i ctureFromURL"
RaiseEvent Lo adF inished (Cancel )
I f Not Canc e l Then
Set Picture = Async Pr op .Value
End !

End Se l ect

End Sub

, , LoadFinished ,
vo RaiseEvent.
Cancel True, .
, Property AsyncRead
CancelAsyncRead, " " .
. pIcturebox control ,
AutoSize .
control:

Pr i v ate Sub picBitmap-Res i ze()


. 1 Picture cont r o l
I f pi cBitmap.Picture <> Then
Us erControl.Si ze picBit map. Width, pic Bitmap. He i gh t
End I f
End Sub

, picture box control ActIveX control


:

Pr i vate Sub UserCo nt ro l-Res i ze { )


If picBi t map. Pictur e = Then

--
picB i t map. Move , , ScaleWidth, Sca l e He i gh t

3 30
Else
If ( Wi dth <> picBitmap.Width) _
Or (Height <> picBitmap.Height ) Then
Siz e picBitmap.Width, picBit map. Height
End If
End I f
End Sub

control . UserControl
, , project . '
Toolbox control AsyncBitmap. declaration
bitmap:
Option Exp lic it
Const DOWNLOADF ILE = "d: wind ows\ s amp l e s\ f i n l\Ar c he s . bmp "

Click :

Private Sub Form-C l ick( )


If Dir$ (DOWNLOADFILE ) <> "" Then
AsyncBitmap l. Pictu re = Lo a dP i c t u r e (DOWNLOADFI LE )
MsgBo x " picture ~~"
AsyncBitmapl .P icture = Lo a dP i c t u r e ( "" )
Async Bitmapl .PictureFromURL = "file: \" + DOWNLOADFI LE
Else
Ms g Bo x " bitmap x~"

End If
End Sub

U , Picture , ;
LoadPicture. PictureFromURL.
file:\. U .
, LoadFinished:
Private Sub AsyncBitmapl-LoadF inished( cancel As Boo lean)
cancel = False
Ms g Bo x " a ''"
End Sub

Cancel False, .

H#itffli ~Ic::l l

. 14.9. ActiveX controI.

--
3 31
OC)( c;oTItrol
OCX AcliveX conlrol
, , , AsyncB~map .
ToolBoxBitmap UserConlrol b~map
Toolbox
conlrol.
, File Make AsyncB~ap.ocx,
. Oplions conlrol,
OCXconlrol 10.700 Bytes.
, Setup Wizard ,
"" conlrol , ,
conlrol Internel, cab.

rpo~ Ac;ttve)( coTIt rol '

ActiveX conlrol L,
OBJECT,
control, , , , ..
ActiveX conlrols Web tag < OBJECT>.
, m ActiveMovie ActiveX control,
L :

<BODY>
<OBJE CT ID="ActiveMov ie l" WIDTH=26 7 HEIGHT=73
C LAS S I D ~ " C L S I D : 0 5 5 89 F A 1 - C 3 5 6 - 1 1 C E- B F 0 1 -0 0 AA 0 0 5 5 5 9 5A "

CODEBASE= "http://www.myserve r.gr/iecontrol.ocx ">


< NAME="-ExtentX" VALUE="7038" >
<PARAM NAME="-Extenty" VALUE="1931" >
<I OBJECT>

lag <PARAM> conlrol, lag <CLASSID>


class idenliIicalion AcliveXcontrol Regislry
i] T . ooi] con-
Irol. control , CODEBASE
URL ' Inlernet Explorer conlrol' m
, control m
conlrol.
CLASSIO conlrol . ,
Microsofl ConIrolPad, ActiveX controls ,
events. .
10 tag <OBJECT> ActiveX control
tag <PARAM> ,

--
VBScript.

3 32

- - - - - - - - - - - - - - - - - - - - -- - -- - - -
< OBJECT > tag, ALlGN
control, BORDER , HEIGHT WIDTH
control, HSPACE VSPACE
control . .

" " cte}{ coJjtrol

, ActiveXcontrols,
"" ,
,
. CodeBase tag < OBJECT >
URL constrol, :
COD E BA S E = "htt p: //actie x .m i c r o so ft .com / control s / co n tro 1 . ocx#Ve r s ion=l, 2, 3"

control.
, control '
CodeBase, .

~E, .CAB .INf

, ,
ActiveX ' tag < OBJECT> . :

CAB
.CAB (Compressed cabinet file) ,
. ,
Lempel-Ziv, Diamo nd.Ee , ActiveX SDK.


PEs (Portable Eec utab les ) .OCX (custom control), . ( )
.DLL ( ) .

'"f
.

Ii IJjterJjet

, , ActiveX control site


; ,
' .
ActiveX,
system administrator. control
. ,
, Internet Eplorer Netscape ,
default.

- -- - - - - - - -- - - - -
--
333
An conten ~. ""''''''~,"",,''''''''''''''~",*~R;
Web gM ~ conn 4ctie COOenl: ltII q oential}o
~~:Ierrts The;e s~ COfbd hoo.o pol~
poblem:s a'! dMk with

S eiIy methxi

r. t{ (ecnneMed w ers)
/! polected IQl serty pob!em$. Poten~
lI'"I$afe contert i$ oide: al"ld yoo ! noI~ed.
r Medun !recommended to e:ert AeI$ aI"Id dev~J
You '! -neo:t .,. fe~ ~You conchoose
whethe noI to vew pedily .ns8! cone.-.

r tlone InoI ~
ou ! noI polected ftorn ~ sedy pablem; , U$e 1
S'eltrg ~ }'CIU! R8'eeI.:I:~ Ir'isj re vJe

0< c.....

.14 . 1 0. Internet Explorer.

Internet Explorer ActiveXcontrol site


, . '
control, 14.11.,
, , CA (ce1i ficate authorily)
control. Yes.
(None)
Internet Explorer, control .

BftI,jJ,i!@i'ffl!tl!fM1i!i!ifflffif!j"t ?' '


Doyou.,;oh loin".. n n lnte'neEbeettooM..... 1 'ill$ :1
""''''
Qd e..chinkbdowI:dore I~ on Ih ce\iicho ~
", . , .. - '" ~ '.' .' "" _ ,0.'
--
.
~
,

; Inle fPflt fxp!ore r B"n on U enu ConlroI ~


i n pl>ll_ by

Niaoso ft ( l
25 2 COI'I01MrcZ! 1HJbJ',"'" rm<N' Cl'Nertzl5 $~ by ,
, Ve riSiqn C91!HI!!HCjf! Softwar e p ubl iWJ;;A ,
""
-.. .. Ex,p;res: 1~?i'!.997
,
.-,; ",- ~

he I.tue. 5-~~n.:;:. 1IU ~ \ ""'....e phh/8j b


Mco....Ccpo""","
r I~oWh ~Iom 6 Corne<ll
S tt-" PI.tIbho, CA
...- 1

. 14.11. l contro.

CA (digital sign)
, Microsoft GTE, control. ,

--
control

3 34 - - - - - - - - - - - - - - -
Internet I, . [ ActiveX controls
,
on HTML.

c:te}{ Doc:ument s
ActiveX Documents,
ActiveX controls, containers, Internet l 3 .
Oftice Binder.
on Visual Basic 5.0
. ActiveX
lJocument. UserDocument,
, , , '
OCX control, ActIveX
, ,
, VBD. lnternet
Explorer, .
L ActiveX Document VBScrIpt
:

<S CRIPT LANGUAGE="VBSc ript ">


Sub Window_ OnLoad
Do c ume nt. Ope n
Do c ume nt . Wr it e "<FRAME SET>"
Docume nt . Wr i t e "<FRAME SRC="" Accounts.vbd" ">"
Do c ument .Write "< /FRAMESET>"
Document .C l ose
End Sub

1. on control -
. control ,
. , control focus,
( on Format).
control container control
textbox control.

2. on frame control control. control


on frame ( con-
trols, captlon , . . ).

3. on hypertext textbox control.


on URL, ""
Internet Explorer .

--
3 35 - - - - - -- - - - - - - --
~,
Kio
{
n IJIterJIet
VisuaI Basic 5.0 ActiveX controls Intemet,

. : Microsoft Winsock Control Microsoft


Internet Transfer Control.
. . TCP & UDP, & FTP.
, .
Project Components Control Tab Microsoft Winsock Control (MSWIN-
S C . C) Microsoft InternetTransfer Control 5.0 (MSINET.OCX) .

, " ,


i C""O; 'I~I @:"""''''''''' .
Microsoft Int~rnetControls
~ iK # % ~'IN;,, 1'. J.i ~ ' I!I
D Mc ;oft Controls5.0
~ ..uJ_~
- ...
.
D MCrosoft ~ked Edit Cotrol 5.0
O fo'iosoft ~ Control 5 .0
Miosoft 0..tIine Control
i[
O !"o'oscft Pi;tU'eQ Control 5.0
i ~ 1::.
':!J

~
O ""=rosoft RemoteO&a Control

MtSOft RemoteQo1J ecrtol2 .0 ::;" EJ 1m
Io\crosoft Rd Textbox cnrol 5.0

D fo'osoft SysIrfCl ContrtIS.o
DMicrosoft abbed DaIog Control5 .Q
"'cosoft wndows Comon Controls 5.0 'If Ilrowse...
Q..!'krosoft:_~ COfMon ctrds--2 5.0 ..:J
.~ - "'"
~rtcr~ ~ Tr5der Cotr!S.O
.!

-
'- loction: D:\WIlM\System32\MSII'Er .oc

" II ~ 1

. 15.1. MicrosoftInternet Transfer ControI 5.0.

controls,

--
TCP/IP, Intemet . .

- - - - -- - - - - - - - - - 337 - - - - - - - - -- - - -- -
CP/IP
Internet , :
CP (Transmission Control Protocol) (Internet Protocol) . 4 (Layers):
Appiication, .
@ Host-To-Host Transport, .
@) Internet, .
Network Access, .

TCP transport layer Network Access layer.


TCP/IP .

.
Client Server. , ,
Client Server . ,
Client Server .

1}
.
4 , 255,
. L 182.45.11.51.
,
. , Internet : http://wwW.
poseidon .gr/Vbonline.
, .. :
.gov = Goverment
.com = Commercial
.edu = Educational Institution
.net = Network
.org = Noncategorized OrganizatIon
.gr = Greece
.jp = Japan
Internet Network Information Center (InternIc).

(I'orts)
Internet.
Internet.
Ports, .
Internet,
Port. , :
(WWW): 80
FTP: 20 & 21
GOPHER: 70

--
3 38 - - - - - - - - - - - -- -
SMTP(Email): 25
3 : 110
L: 23
WHOIS: 43
FINGER: 79
,
, .
. hosts,
Windows : 89.0.0.107 www.address.com.
, Domain Name System
(DNS) .

Soc:ket5
Socket . ,
sockets, Barkeley Sockets,
Intemet, Windows Sockets,
Windows. ,
WinSock, m ,
TCP UDP.

Mtc:r050ft WtJ)50ck c:.oJ)trol


ControI Windows
Sockets. ,
, Controi.
WinsockControi.

BytesR eceiv.d Bytes .

LocalHostName .

LacallP .

LacalP o ~ E Joo / .

Protocol / .

RemoleHosl .

RemoleHostlP .

RemotePM / .

SocketHandle handle Socket.


Slal. ad Socket.

--
Winsock Control.

3 39 - - - -- - - - - - - -- - -

AboutBox Winsock control About.


Accept .

Close .

Connect .

GetData .

Lste n .

PeekData Buffer.
SendData .

Winsock Control.

Clase .

Connect Kjp .

ConnectionRequested .

DataArrival .

SendComplete .

SendProgress .

,IILJ)SOC:k., lJ)terJ)et traJ)sfer TC


controls Winsock Internet transfer
CPIIP . , Settings : Control Panel
Start Button Networks,
15.2.
?

.f1e~I'Seice" \"iotocob ~~ I~~]


!:!etwok PrOOx::

'rNetBEUI P!otocol
" N'W'l..IFWS P ~ibII ,~
"N\ILd. NetBlOS
'rCP,otocoI

. . Ber.e
O,,~
.. ..< CoMoI ~ 1 co:r.>: e comect10 f1IBM
nr/,,,,,,,,, d m rers ..tCh'ld dfec Mt","""
_d

--
. 15.2. NETWORK TCP/IP.

3 40 - - -- - - - - - - - -- - -
TCP/lP WINIPCFG.EXE
Windows 95 IPCONFIG.EXE Windows .
Winsock Control, LocalHost LocallP,
. ;
control Form_Load :

Private Sub Fo rm-Load { )


Caption = Winsock l.LocalHastName & ~: ~ & Wins ockl. LocalIP
End Sub

Protocol TCP D 0-
skcTCPProtocol, 1-skcUDPProtocol. SocketHandle
Winsock Control.

crteJIt
Client
Connect, RemoteHost
RemotePor!

Winsock l.RemoteHos t ~ 1 9 9. 2 1. 3 3. 10 1"


Winsockl.RemotePo rt = 1066
Winsockl.Connect

1066, 1 1024
, Serices Windows.
State ,
Connect:
Pr ivate Sub Wins ockL-Connect {)
If Wins o c kl .State = s c kConnect e d t he n
Print nConnect ion Succe s s f ul W

end i f
End sub

State :

SckClnsed Socket .
SckClnsing / .

SckConnecIed .

SckConnecting .

SckConnectionPending Sncket / ,

SckError .

SckHostResolved Socket .

SckListening Socket .

SckOpen .

SckResolvingHost Socket .

--
3 41
SendData , . .

Winsoc k.SendD a ta ~Hello "

DataArrival,
GetData .
, Client Close, .
C len b Winsock Control ,
True AutoRedraw ( , ;)
Buttons, [ :

CIose Connec1ion j

': ~ '

. 15.3. WinsockControl Buttons.

Option Explicit
Private Sub Fo rm-Load( )
Caption = Win sock l . Loca lHo stNaroe & ": " & Winsockl. Loca lIP
En d Sub

, K~O

Priva te Sub c mdCo nnect-Cl ick()


Winsockl .RemoteHast InputBox( "Enter r emot e host ( addre ss or name) ")
Winsockl .Remo t ePo r t = 1066
Win so ckl .Conne ct
End Sub

'

Private Sub cmdSend-Cl ic k ()


I f Win sQckl . Stat e = s ckConnected Then
Win sockl . SendDa t a I n pu t Box ( "Enter dat a to s e nd " )
Print "S e nding data to " & Wi nso c k l. Remo teHo s t I P
Else
MsgBox "No t c urren t l y c onnected "
End If
End Sub

, i Ql Q n

--
3 42
Private Sub Winsock l _Connect( )
I f Winsockl.State = s ckConnec ted Then
Pr i nt ~ Co nne c t io n successful! W
End !
End Sub
\ oo ~ 11 client 1

Pr ivate Sub Winsockl-DataArrival(ByVal bytesTotal As Long )


Di m vtData As Variant
Winsockl . GetData vtDat a, bString
Print ~Got data ~ & vt Data & " from" & Winsock l . Remot e Ho s t IP
End Sub
\ 1 ~o Socket

Private Sub cmdClose-Click ( )


Wi nsockl. Close
End Sub

Server
Server, Client,
. l acalPort
Client. , Lst en , Server
:

Wins oc kl.Local Po rt = 1066


Wins ockl. Listen

Client Connect, Server


Connecli onReQuest, Server Accept.
Private Sub Winsock1_ ConnectionReques t(Byval reque s tl d as long )
Wins ockl. close
Wins ockl.Accept Request ld
End Sub

ReQuestld .
Server Sockets:
Clients Client.
Accept, Server
DalaArrIval GetData SendData. D
Client , Server Close,
server .

P riateSub Wi ns oc k1-Cl o se()


Winsockl.close
End sub

--
3 43
Serer
Serer.vbp:

Option Exp l i cit


Pr ivat e Sub For.m-Load ( )
Form l. Sho w
Caption = Winsockl.LocalHostName & ": ~ & Wins ockl.Lo ca l IP
Winsockl.Lo calPort = 1066
Pr int " : " & Win s o ckl. Lo c alPort
Wins ockl. Li s ten
End Sub

yo~ ConnectionRequest oo~.~ . client


OK~1 .

Privat e Sub Wi nso c kL-Co nnec tionRequest (ByVal re que s t I D As Long )


Pr i nt "Conne c t ion re qu e st i d " & requestI D &
" from " & Win s o c kl.RemoteHo s t IP
Wins ockl . Cl ose
Wi n sockl. Acc e pt r e que s tI D
End Sub

DataArrival 1.1

client .

Pr i v ate Sub Winso c kL-Dat aArriva l (ByVal by t e s Tot a l As Long}


Di m tData As Var iant
Winso ckl .GetData vt Dat a, vb St r ing
Print "Rec eived: " & vtDat a & " f rom " & Wins ockl. Remot eHo s tIP
vt Data = UCa s e (vtData )
Print "Se ndi ng: .. & vt Data & .. to .. & Winsock l . Rernote HostIP
Wi nsockl .SendData vtData
End Sub

Close O01~ client ~

Pr i vate Sub Winsockl-Clo s e()


Pr int "Conne c t i on c losed "
Wins o ck l. Cl ose
Pr int "Listening to po rt: " & Winsockl . Local Port
Winsockl . Lis t en
End Sub

Client,
Connect / , .. 127.0.0.1.
Serer Send.

--
Close, 15.4.

3 ......
_ D

i$ter8g 10pl' 1>6


E:rnectior I~ d 104 Jrom 1270.0.1
Aeceied: Tett oWnocl<, cooIroI frcm 127.0.0.1
S~ 5 \Y1 N50C CON RO L 10 127.0,0.1

"""""'" ""'"
Lislennj 10pt 1006

. 15.4. CIient Server.

l,} nn Serer

Client Serer .
Cl ents, Winsock Controls.
Winsock Control
Index, , .. :

Load Winsockl (NumberOfSocke ts ) .

, control ,
control ,
ConnectionRequest control Load, .. :
Private Sub WinsockL-ConnectionRequest(Index As Integer, ByVal requestI D As
Long)
Print ~Co nne ct ion request id ~ & r e qu e s t I D & _
~ from ~ & Winsockl (Index ) .RemoteHost IP
NumSockets = NumSockets + 1
Lo a d Winsockl (NumSockets)
Wi nsockl (NumSockets) .Acce pt requestID
Win s o c k l ( O). Close
Wi nsockl (O) . Li s t e n
End Sub

Serert.vbp , Serer
:

Option Explicit
Dim NumSockets As Intege r

Priv a te Sub Fo r.m-Load ( )

--
3 -45
Fo rml. Show
Caption = Wins ockl ( ) . LocalH os t Name & " : " & Wins oc kl ( ) . Loc a l I P
Wi ns ockl ( O).Lo c alPort = 1066
Print "Lis t ening to po r t : " & Winsockl ( ) . LocalPort
Winsock 1 (0 ). Listen
End Sub
ConnectionReque st n 1 L1 c lient
1 .

Private Sub Wi n sockl _ ConnectionReque s t (Inde x As I nt e ge r. 8yVal r eque s t I D As


Long )
Pri nt "Conne ction r e qu est i d " & r e ques tI D & " fr om "
& Winsockl ( Index).RemoteHostIP
NumSoc kets = NurnS oc kets + 1
Loa d Winsoc kl (NumSoc ke t s )
Winsockl (NumSockets ).Acce pt r e que s t I D
Winsockl (Q ).Close
Wi nsock1 (O). Listen
End Sub
DataArrival L1

client .

Private Sub Wi ns oc kl -D ataArriva l(I nde x As Inte ge r . ByVal bytesTota l As


Long )
Dim vt Dat a As Var iant
Wins ock l (Index ). Ge to at a vtData , vbS tri ng
Pr int "Re ceived: " & vtD at a & " from " & Winsock l( I nde x) . Remot e Host IP
vtDat a = UCa s e (v tD ata )
Print "Sendi ng: " & vt Dat a & " to " & Wi nsoc kl (Index ). Remot e Hos t I P
Wi nsock l ( I ndex ). SendData vt Da t a
End Sub
Close i c l i e nt 1

Pr ivate Sub Winsoc kl-Close(Index As I nt e ge r )


Print " Conn e c t i on c los ed: " & Wins o c kl (Inde x ). Remote HostIP
Winsock l ( Inde x ).Close
Unloa d Wins oc kl( I ndex )
NumSoc ke t s = NurnSo c kets - 1
End Sub

"r o\\o

User DataGram Protocol TCP,


Network Layer . TCP

--
Sever , , '

3 46
TCr/lp. .
Internet. , Serer
13 ti ck.usno .nay .m il (19 2 .5 .41 .40 ) :

Option Explicit

Privat e Sub Form-Load( )


Wi ns o ck l. Connect "t ick. usno . navy. ." , 13
End Sub

Pr i v ate Sub Win s ockl-DataArri va l( ByVa l by t es Tota l As Long )


Dim myData As St rin g
Winsockl.GetDa t a myData , vbString
Text l = Te xt l + myData
End Sub

MLcro soft lJ1teret Tr i'J1sfer COJ1tro'


MSINET.OCX control
Internet, , Secure FTP, :

AccessType / Proxy ' .

Document / Serer.

Hinternet Intemet Handle ' controI.


Password password .

Prolocol URL.
Proxy Proxy Server Internet.
RemoteHost / .

R e mote Pot / Inlerne!.


RequestTimeout E/roo rm .

ResponseCode .

Responselnfo .

StiltExeculing Status Control .

URL E l/oo URL Control.


UserName .

Microsoft Internet Transfer Control.


Cancel .

Execute .

GelChunk .

GelHeader .

OpenURL ..

--
, Control.

3 47

StateChanged Status j .


Hypertext Transfer Protocol () FTP TELNET.
, Internet Serer 1.0.
Internet, .
(Application layer)
Internet. :

{Method] [requesLURL ] [HTTP_Version]


[He a de r l _ f i e l dn ame ]: [ fi e l d l _ v a l u e ]
[Header2_fieldname] : [ f ie l d 2_ v a l ue ]

[HeaderrL.fieldname ] : [fieldN_value]

ldata]

Get /Default.htm http/l.O


Accept : image/gif *. *
Accept-Language: en

User-Agent : Spy
<HTML><Hl>Hello, World.</Hl>< /HTML>

Get URL.
Head .

Post Sere r.

Put , .

,
Sere r .
CR/LF .
Serer :

[HTTP_version] , [Status_code ] [ReasoIL.phrase]


[Headerl_fieldname] : [fieldLvalue ]
{Header2_fieldname]: [ f i eld 2_ v a l u e ]

[ He a de r N_ f i e l dn ame ] : [fieldR-value ]

--
[data]

3 48 - - - -- - - - - - - - - - - -
, Microsoft Internet Explorer :

Get / de f a u l t . ht~ HTTP/l .O


: image /x-bitmap, i mage / jpeg. * 1*
image / gif,
Accept-Language: e n
User-Agent: Mozilla / 2. 0 (compat ible: MSIE 3.0 1; Wi ndows 95 )
Conn e ction ?: Keep -Alive
I f -Modified-S ince: Sunday,2 4-Nov- 9 6 10 :05 : 30 GMT

, URL .
Internet
Browser. Keep-Alive
, If-Modified-since
.
Se ve r , :

HTTP/l.O 200 ok
Server: Micros oft -II S / 3. 0
1 2 1 99 6 1 3 : 32 : 1 0 GMT
Dat e : Sun,
Cache -cont ro l : pr ivate
Content - type: tex t / h trnl
Expires: Sun, 12 1996 13: 32 : 10 GMT
Set -Co okie : ASP SESSI ONID=QXXBABBAXGVJP GMUi path= /
Ac cept-Ranges: bytes
Last -Mo d i f i ed: Fri . 09 J u l 1996 04: 0 0 :00 GMT
Content-Length: 405 1
<HTML>Some da t a-< / HTML>

, status 200,
, , application
sever . GR/LF L.
OpenURL .
URL
textb o control:
Text l = I n et l .0pe nURL (~http: / / www .mic roso ft .comW )

Protocol,
:

In etl. Proto c o l = icHTTP

Protocol.

IcUnknown .
IcOefault 1 l! Protocol.
IcFTP 2 File Transfer Protocol (FTP).
IcGopher 3 Gopher protocol.
I c 4 HypertextTransfer Protocol () .

--
I c S 5 .

3 49 - - - - - - - -- - - - - - -
Httpspy.Vbp Internet transfer control,
Internet . controls
15.5.

.. HTTPSr ~.
HTJPS~

1~ II_ DcotOltcom

Aetuned .... ~ade $,;


ReI~HML

:J

[
. 15.5. .

Opt ion Explicit


Pr i v at e Sub Command l _Click ( )
Error GoTo latho s

Text 3. Text I net l . Ope nURL ( Te x t l . Te x t)


Te xt2.Text = Ine t l .GetHeade r
Ex it Sub

l atho s :
Text2 .Text = ""

Text3.Text = ""

Ms g Bo x Err. Des cription, "Error: " & Err.Number


End Sub

Private Sub Command2-Cl ick ()


End
End Sub

nw Sct >

; Secure
Sockets Layer (SSL) . , Server
CP/IP . Intemet,
UserName Password intemet transfer control.
( Client Server,
server) m, -

--
3 50
.

'


.
, PC MS-DOS Windows.
Intemet transfer control FTP
, Eecute , ,
VBTooIs FTP Serer Microso:

Inet l . Ex ecute ~ftp : / / f tp .m i c ro so ft .comn , ~ GET VBTOOLS .txt c : \VBTOOLS. t xt"

Execute ,
.
StateChanged control Status.
, :

Pr i vate Sub I net l-StateChanged(ByVa l Stat e As Integer )


If Stat e = i c Re spo nseCompleted Th en
Ms gbox = Inet l .GetChunk (O )
End if
End s ub

State:

IcNone '{ .

IcHaslResalvingHasl 1 conlrol ) Host.


IcHoslResolved 2 control Host.
IcConnecling 3 control Host.
IcConnecled 4 control Host.
IcRequesting 5 control mov Host.
IcRequestSend 6 .

IcReceivingResponse 7 Host.
IcResponseReceived 8 Host.
IcOisconnecting 9 / .

IcOisconnected 10 / .

I c r 11 / .

icResponseCompleted 12 .

GetChunk , .. :

Filel. txtCRLFdi rname/CRLFfi l e 2.txtCRLFCRLF

; '' ,
:

--
3 51
Pos it ion = -1
Di rectory = Inet1.GetChunk( Q)

NewPosition = In Str(Po sition + 2, Dire c to ry, vbCr + vbLf, 1 )


If NewPosition = Len( Directory) - 1 The n Exit 00
One f i l e = Mid(Dire ct ory, Pos i tion + 2 , NewP osition - (Po sit i on + 2
Pos i ti on = NewPo s i t i on
Lo

Ftp.Vbp intemet transfer control


Windows FTP Client. labels, Textbox
Gommand8uttons,

... .....'nFTP E'J


_ .................._ .......' ".


! ft:Jt. icmot com

. 15.6. .. (160)

Optio n Exp1 icit


Dim Bus y As Boo lean
\ Ft p se rer .

Privat e Sub Command l-C lick ( )


Busy = Fal se
List 1.Cl e ar
If LCa s e ( Le f t (Textl . Te xt , 6 = "ft p: / /" And Len(Text l. Text) > 6 Then
Inetl . Exe cut e Textl . Text, "D I R"
El s e
MsgBox "Syntax : ftp : / / name"
End If
End Sub
, VlQ .

Pr i vate Sub Command2-Click()

--
35 2

- - ------
Bus y = True
I f Listl. List (Li st l . List l ndex) = " " Then
Ex it Sub
Elsel f Listl . List (Li stl. Listlndex ) = " " Then
Inetl . Execute Te x t l . Te xt, "CD " & List1 . Li st(List l. List lndex )
El se l f Right (L ist1. List {List1. Listl ndex ) . 1) = " j " Then
Inetl. Execute Te xtl . ., "CD " & List l . Li st ( Listl . Li s t l n de x)
Else
CommonDialog l . file name = Li stl.List(List l.Li st lndex )
CommonDi alog l. ShowSave
I ne t 1. Ex e c ut e Text 1. Text, "GET """ + List1. List (List1. Listlndex ) + """
+ CommonDi alog1. fi l e n ame + "" "

End If
End Sub

, n i~ l Q ~ K ~ .

Private Sub Inet 1-S t ateChanged (ByVal State As Intege r )


Di m Directory As Stri ng
Dim Po sit ion As Lon g , Ne wPosition As Long

If Busy = True Then Exit Sub


If State = icResponseComplet ed Then
Positio n = -1
Directory = I net l .GetChunk (O )
Listl.AddItem ".. "

NewPosition = InSt r ( Po s i t i o n + 2. Di r ecto ry, vbCr+ vbLf, 1)


If NewPos ition = Len (Directory ) - 1 Then Exit Sub
Li s tl . AddI t e m Mid(Di recto ry, Position + 2 . New Pos ition - (Po sition
+ 2
Po sition = NewPo s it i o n
Loop
End If
End Sub

JjJj

Winsack Control , client


sere r. SQL , MS Access
Biblio.Mdb. , ; ASCII
client, ' Grid control.
.

--
35 3
Hefp

, . Windows help.
, ' ,
, help, ,

, Internet Explorer . .
help :
(HelpText ) RTF.
f9 Help Project (HPJ).
~ (compilation) Help Compiler Help
Project.
Help ,
Visual Basic.

i\" _ ' " ;!! j. . :

!).& ,dt ~ ~tr~~ooIs: T#e 'J!bN ~ ~~


I D .., iiia ~ ~ ~ @<1~ . "''6' El!Ll U;; B ~
tcwm.. - .- 9 .I~ . ~'Fiii~= :: ;,;~ ~
I~ "
,. '1 - , . ). . 4 ' , . ~ . , . , . , 7' ,
' ,' 11' 'U '
"11 " , . 1) " .
._ _ _ P_ oe'.

"',
Eo11':1('tAnsi Mrtl o d

6( tmm: 10 u., ,c f(pQ(o I ~ I: t'I'- ~ ~ ANSI

~~~!:~X~~00' lI:,,c 1ItX:o ~"'. "'. ,. cm:-J


....
~ o It/o
10

,_ ....
rIIItSr l\IttlIod

tIooq 10 <1Q!:>'O . 00 ..... l" 11);; ..i 8. IJt ~h kt'O(


~ I K';p(( :; '< ~ JDt,l. \.Q,( 111 1 (I(j 100 v8Jou[ ".. , TRVE

,..s,
nt)ivo lRg hl IITIV fJf:. ( 0IIUI.Jt , ty .o "- LJ[l(q

...
'
.J~:I~~Sh i\ l tt IIo,!
Pq ~_I IW6~Ai ~,br"i7
P_&-e+

,...".c
j

--
. 16.1. topics. page break.

3 55
, help
RTF. ,
TgstrIng.Rtf, Microsoft Word 97.
, topics. topIc . ,
(hypertext),
topiC. Page break
Insert Word.
topiC, (con-
text strIng). footnotes Word,
, topic .. topic.
, Insert, Footnote...
Custom mark. textbox tootnote . ,
, #,
$. , 16.2., Footnotes
. context strIngs ,
.
Footnotes . , topics
History, Bookmarks, Topics Indexed Search Results help.

-~~___ , . plQer"';; , _ _,_" ~_._ ._~ _. _ . ~_

'" .
E},.tractAnsi MetlIod .1.J
m pE (fI "" ltlQ(oo ~ , ANS/
,
vo[ Ci 10 " , ll( lt lQl VO _ EIC

---~~~=----.-. ~e~~ ---------~


~es'Al fooootes =J[~C= @~
j
yr m
~xr~cAn<~
o,Ex~.cAn"
$Extt"ctAn.; M. thod ~
+220;


H/3fi #. n ( m~~ h

. 16.2. Footnotes Word.

footnotes , topiC
footnotes .
Footnotes Insert.
footnotes - +
topiCS (groups) .
topIcs Word
. topic

--
' help. ,

3 56 - -- - - - -- - - - - - --
Format Font , Underline,
,
Double. ,
context string topic.
Font, hidden checkbox. .
double underline hidden context strIng
topic, , TakeMemoField
16.3. hidden
Show/Hide toolbar Word.

W .l; \Iold TGSTRING I!!

f.iIe ~dit !!iew l~t..fqrrw: 10015 ~ :!ii'1CIow t!~ ~itl


r;;;:!8J i:!I g: .~]_ <{~,,;;' :* ' ~ .; ~J EI1II!m i;"i ".i"
~ "'., " 'J ; i. i m ,!" ,!"
, \i~ ' , . 1 . , . ~ , 3 ' . 4 ' , . s. ,.&. . 7 ' , . ~' . 1~1O ' 1 ' , ' 12' , ' 13 ' ' ...

~"----,---------~,---------,- P4ge Break__ ".-- ,..- - ---..-.-- ..- --.- ....,.-.-.- .....----.....-.----"!::.
m '+1f
App endMtnlOFi el d 'l\fe th o d~
.~
' 8 0 - r - ' f l d - i - l -tt e ss - .- Q - 1 - !
- ulT1f. .' ' 'io' - - ' Memo - LongBnary." np
m?lI' ,. IakeM emQFje'[n)t~M_~l@f.~!4 - - - '. - 10' )
.
vo,l m;lu .1 _

v"r t1l
1>,;, ,''' " M".m" r;"'.MI(i/d.A <~;.,M)II -;-
Eo ~ . ~

faQe 2 1 2/~ Sn. .Ln7 CoI. ~ h

. 16.3. .

double underline single, help


topic. topic
help help. hid-
den context string
@HelpFile.hlp hidden . , topic context string
HelpFile.hlp.

Help project
, ,
.. , help project,
help. ,
HPJ. , RTF
help, help .
HPJ :

[OPTIONS]
COMPRESS=lQ p h rase Zeck
OLDKEYPHRASE=Ye s
LCID=Q x 4Q8 ; Gr e e k
CHARSE T ~1 6 1

CONTENTS=main

--
TITLE=TgS tring Class

3 57 - -- - - - - - - - - - - -- -
COPYRIGHT=(R) Tangram Cl a s s Ac tion Ve r 1 .0
CITATION= (c) De mo s t he ne s Poseidon 1 9 9 5 - 1 9 97
BMROOT=D : \VBONLINE\voI3 \source\help
HLP=. \ t g s tring . hlp

[FILE S]
tgst r ing. rtf

[ ]

main=1000

[WINDOWS]
main= "" " 60672 , (r14876671), ( r425958 4) , f2
secon d="" , (6 53, 102, 360 , 600) , 4 , (r 1487667 1 ) , (r4227327) , f 2

, HPJ, OOS HC
Visual Basic. (compiler)
HPJ help.
OOS, :

Hc Tgstring.hpj

Microsoft Tools CO
Visual Basic HCW. .
, Microsoft l Workshap,
HPJ l , " "
OOS hc campiler.

?" MICfO;OH : W olk shop g ~l lIng] I!!lIiI EJ


i ~ fie YeIII ~ndow ! e$\ .QOO tie/p

~1 i;BI f1!1 ;[1'iI)


He~ Fk: I\tgstringhlp
; h~ Ne;s mrained by HCW. 00 roI rnodi/ylhi!: fk ciectly,

IOPTlONS]
COMPRESS..10 phraseZ ecl:. "", 1
OLOKEYPHRASE",Yes
REVlSION500No W"",",
<4 0 ; Gleek
REPORT..Yes
QiAR5ET..161
""""
CONTENT5..rMin ", . 1
" gSITi1g C1!.ss
COPYRIGHT,,[R) Targam ClassActione 1.0
TAT!O N ~lc) Oemos.hees pooedon 19951997
.......
-"O : \VBO N LI NE \voI3\souce\help
g;;,j..
[FllfS]
Ig$Irir"g,rIf iCl\F]

. 16.4. Micrasoft Heip Workshop.

16.4.,
, HPJ .
OpIions... [ help, , topic

--
3 58 - - - - - - - - - - - -- - - -
help .. , FiIes... RTF
help. Windows...
help.
default , topics
. Windows... m
detauit . Windows Properties ( 16.5.)
, m , ,
Buttons scrolling scrolling .
; . m topic
Paragrah Format.
topic ,
Paragraph Line and Page Breaks Keep with next.

?! '

Wndow ll!bul:et

r. ~ r M><iize...mow
~uHeb...inck>w<)nkp

. 16.5. .

'"
,~

~OOerMI
,'"'- ""'"' "..1""
Jnde>c ~
...
iI<
-

"
TgString

TgSlrin g C ~ IiluDPIO!1 " . BoIio~ M1tt\

:.:~~.I;~~11!~;O ", roe:I e:l) .?I II@!


EI(J1 'mK I .\Ye::
.mid j,j
~
Attach M~tho II
Di .. 0;3 3 ~ To;S t t 1n q

TgStr . At t.ach " <~ "


fls !J ox TrS t t . .ns lTOOe1it
8
lo4tl. O~ tO.ol
l( 8 !:<P'!'oolol' lI
,~
.. .. "l) 10 Q4 llK .
, u w l U , e: l
What10 do <. ! l lj1r1~ l( J';D< l ttl ,!
u90 OlO tl(l1OC<tOLNUQ l8unf t
:kt~1!

N.tl
Obftd.M>eJ (JI < Slring)
.:J

. 16.6. uv .


. m

--
topIc ' . topic Attach -

3 59 - - - - - - - - - -- - - - -
second Attach
. :

ttach~ At tach>second

attach >second hidden . JX 16.6. help,


. scrolling
, .

'
Paste no xo RTF.
m ,
RTF. , hypergraphics.
:

{bmx picturefile}

, r c ,
. ctrefile .
' 8itmaps... Microsoft
Help Workshop. 018, WMF, SHG.
hypergraphic s Hotspot Editor.
, topic.

Hefp
'
50 .
topic , hidden , ! '
.
Notepad. :
~ v !e crgram ( calc .ee' , )

! Eec Program (' calc . exe ' ,} hidden. Ee cProgram


.
.
,
" . ,
.

Back c .

Contents Contents c hlp.


CreateButton button toolbar hlp [CB).

- - - - - - - -- - - - - --
--
360

History history list.


N el topIc.
Prev topic.
Search Search.
InsertMenu menubar help.
AppendItem menuitem custon .
BookmarkDefine Bookmarl< Oefine.
CapyTopic topic clipboard .
HeIp.
JumpID ' topic.
D ' topic ' -
( ) .

he n - he n se marker
RegisterRoutine pvj LL (RR).
CIoseWindow ro .

SaveMarl< marker topic.


ExecProgram ) .

Vs ual Basic
Exec, .
, ,
. . . ,
, !ep ("exec B oaUt. avj " ) hidden :
H
1 AV I!ep (~ e xec Boat-l i t . av i ) .

GoWeb. URt.,
Internet Explorer URL.
, ( 18)
RegIstry
Intemet EpIorer:
Private Declare Function RegOpenKeyEx Lib ~ advapi32.dll Alias
~ RegOpe nKe y E xA (ByVal hY As Long, ByVal l pSubKey As String, ByVal

ulOptions As Lo ng, ByVa l samDesired As Long, phkResu lt As Lo ng) As Long


Private Decl are Functi on RegCloseKey Li b ~ a dvapi 3 2. dl l H (ByVal hY As
Lo ng ) As Long
Private De c l are Fun c tio n RegQueryValue Lib "advapi 3 2 . dl l H Alias
"RegQue ryValueA H ( ByVal hKey As Lo ng, ByVal lpSubKey As String , ByVal
lpValue As Str i ng, l pcbVal ue As Long ) As Long
Pr i v ate Declare Fun c t i on RegQueryVa lueEx Li b ~ advapi 3 2 .d ll H Al ias
"RegQueryValueExAH ( ByVal hKey As Long, ByVal l pValueName As St ring, ByVa l
l pRe s e r v e d As Long, lpType As Long, ByVal lpDa ta As String, lpcbData As
Long ) As Lo ng

--
3 61
Const HEY-CURRENT_U S ER : & 800000 0 1
Cons t HEY-LOCAL-MACHINE : & 80000002
Cons t EY-ALL-AC CE S S : & + & 2 + & 4 + & 8 + & 0 + & 20

Const MAX-LEN = 255

Sub mai n ( )
Dim hey As Long, Res As Long
Dim Buf f e r As Str i ng
Loca l Erro r Resume Ne xt

com$ : Cornrnand \ URL


Buf f er : Space (MAX-LEN)
Re s = RegOpenKeyEx (HKEY_CURRENT_USER, "So ftware \ Microso f t \ I nt e rne t
Explorer\Main", ByVal 0&, _
KEY-ALL-ACCESS, hKey)
I f Res = Then
RegClo s eKey hKey
RegOpe nKeyEx H KEY~CH I N E ,
~ S o ft w a re \ M i c ro s o ft \W in dows \ C u r r e n t Ve r s i o n \ Ap p

P a t h s \I E XP LORE .E XE ~ ,

ByVal 0&, EY-ALL-ACCE SS , hKey


Buffer 11

RegQue ryValue hey, ~" , Buf fer, MAX-LEN


RegClo seKey hKey: Buf f e r = Tri m(Buf f e r)
i : InS t r( Buf f e r, Chr$ (O) )
I f i Then Buf fer Lef t $ (Buf fer, i - 1)
She l l Buf f e r + " " + com$, 1
End I f
End Sub

GoWeb
:

s i t e www.po s eidon .gr / vbonline !e p( "g oweb www.po s e i-


don .gr / vbonline") .

J]oj

,
DLL ( DLL 18).
RegislerRauline (RR), :
Regi s t erRoutine( DLLName , Funct ionName , Parame t e r Spec )

DLLName DLL, FunctionName ParameterSpec


,
. : :

~retu rfi-type=par ame t er_types"

--
reUm_type -

3 62 - -- - - - - - -- - - --
, parameteUypes
, , ,
return_type= ,
return_type parameteUypes
, S .
RegisterRoutine help.
snd PlaySound RTF Config
HPJ, Config... Micro soft Help Workshop:

Reg iste r Rout i ne( UMMSYSTEM" , " sndPlaySound", "S u")

help.
Tgstring.Hpj BrowseButIons,

topic, InserfMenu
, Appendltem menu items , ,
RegisterRoutine.

[C ONFIG ]
Br owseBut t ons ( )
I nsert Me n u( " Meo u-To ol s " , " &To o l s" , 4)
Calcu lato r
Appendltem ( "Menu-Too ls" r " Ca l e-I tem ", "&Calculator" , ' ( " calc . e xe' , )")
; Notepad

endtem("en-ls" , "Note-Item", "&Not ePad" , "EP ('notepad. e xe' ,O )" )

Regi sterRoutine ("MMSYSTEM" , " s ndP lay Sound ", " Su")

sndPlaySound, :

TgString Ql! s ndP l a S u n d( ' se id n . wa v " 1)

terp

HPJ RTF,
hlp, . Save and Compile Microsoft
Help Workshop. .
(warning) .
, help. ,
Run WinHetp.

Kjo te rp n ] 5 a5 C;

hlp
Visual Basic Context-Sensitive,
hlp F1. vx Help File
Projecl Properlies hlp.
,
hlp Systems

--
Windows.

3 63 - - - -- - - - - - - - - - -
topic F1 Contents
Options HPJ ( ), HelpContextlD
controls , F1 topic,
control (focus).
. context string topic Map...
Microsoft l Workshop, Map HPJ.

[]

main=1000
Attach=lOlO

help , ,
WinHelp, 32-bit :
Private Declare Function WinHelp Lib uuser32" Alias ~WinHelpA" ( By Val hwnd
As Long, ByV al lpHelpFile As String, ByVal wCommand As Long, ByVal dwData
As Lo ng) As Lo ng

\ vl topic i~al l
Con s t HELP_CONTEXT = &1

\ il help
Cons t HELP_QUIT = &2
, vil index
Const HELP_INDEX = &3
\ l help
Cons t HELP-HELPONHELP = & 4
\ il l Vl I n dex
Con st HELP-SETINDEX = & 5
\ i l topic lQ keywo rd
Con s t L- = & 101


wCommand. hwnd , IpHelpFile
hlp. :
WinHelp Me .hwnd , App.Path + "\TgString.h lp" , HELP_INDEX, CLng(O)

[ , , help ,
. , :

WinHelp Me.hwnd , App.Path + ~ \ T r g S t r ing . HLP", HELP_QUIT. CLng(O)

, , ShowHelp
CommonOialog control:
Const L- = &H10l
Const HELP_INDE X = &3

, Help .
CMDialogl.HelpFile = App .He l pFile
CMDialogl.HelpCornmand = HELP_INDEX

--
CMDia logl . ShowHelp

- - - - - - - - - - - - - - - 364 - - - - - - - - - - - - - - -
Crystff Reports
Crystal Reports, Visual Basic,

,
: . ReportDesigner Add-
Ins Visual Basic, ProgramGroup, . ,
interface, report, FILE :NEW REPORT
, report, Crosstab Report & Mailing labels.
, (
BIBUO.MDB). report sec~on, Page Header, Details PageFooter,
( 17.1.).

.. _ "

'" "' "'~ ,,~x O",'M~ ..


. .
O ~ 'II !i l3 J1 x~ e ' i: OL =oCJo" '1?
T.me s Now Ro ",.... ... 22 ... D r : . .. .. : .
- , .. _ D

'
"q .. ~ .. .,. ...
>\uthol's Repolt
:
b'"
D_I.

P1oq" IDOIM
.~jj ~ j j ~ j j

R.eo t ~~ .." RepOtl "


......
!~ . [(~
r;.
,
. Ull>o
.. ....
, !!
>-
----f>u.,.' s~ ..,. _
P"bID

:j;i~ ~f;,. ;;,,<.:2': :. Comp,, "y " .. " .:.

i' "'; ,~r:!,i:'}::" I ~ I~ . """, .. f o " De''''" [


'-
l :3 .39 RI." At!bo,. Rtpor1

. 17.1. re .


Insert Database Field, - , Detail Section report.

--
Pageheader , -

3 67
, (..
, 55555... , y-MM-DD . .) .
, Insert:Text Field,
Page header .
click textfield, ,
, , , , , , .
special fields, , ,
Group.
, Insert :Graphic Page header
.bmp, .gif, .pcx, ., .tga Insert :Object
Excel, OLE.
! Prevlew File menu,
17.2.

Authors Report r. 09f101lW1

-d-.P
2~).(r
3.1o(.R", !/! 3 54.00
4 Adenn. V..gna
~ Mr.,...,.", b M:~ P
6.An1. Stt= E
7 ~or. L . J" 'f< e
Al .)d';ch.> , I R
9:Avis<>n.D ,
10 ~ard, Di<1t 1.941 ~6.00
1 Begel Fcb ord
12 Bww,Lua
4 ~ 1<>11 . ,;;:" Q. .;; B cad! Clo 2119 2U 5& 1, I DD",

. 17.2 Report .

, Preview ,
, ,
ASCil, txt, doc, r, xls, dif, CSv
E-Mail.
File:Print : ,
report, .
Report fonnula fields.
,
.

menu Insert : Formula Field
Edit Fannula,
, Crystal Reports,

--
.

3 68 - -- - - - - - - - - -- - --
formuIa,
( 17.3.), :

Yea r ( To day ) - {Autho rs.Year Born }

, Button Check.

FJelds: , Funetions' - O Il ol O S ;

Re po lt Fiel ds:
lhS .Ve " , ,
Au!ho ' s.Au_lO =
~
Arilhmeti c:
Rem" ind" , (num. d "nom )
Abs ()
( )
=
= ,,-,. , ""
i
Ari1hmet ic '

S ubutIet =
~

.F (
Au!hoIs.Au!ho r Round l l


@"
(
r~und (. # plo c e s )
" ,n r-"I.. (.
,r- .t?i ,,_PI,r..
~ Dii de
nl
.
. ~'* 'Th ~. ~ .,,,,
FDrmula 111><1: ==:' i
jYe..., (Tod y) - {"'h,s .e ,}
"""'" '" "'" """'~. .

~ .
..

=l 111
"'"'" ~~_tt I .'W~" " "'I' [) LL """~' L
t!elp

. 17.3. Formula fields.

,
.

;J) fOfrnUr1.l ferds


; formuIa fieIds
Crystal Reports:
, ..
{Authors.Author}.
, .. {TotaIVaIue} .
,
@, .. {@TotaIRecs} .
:
- , .. {Authors.Author} .
, . . (1 , 2, 3.14) .
- , . . " ",
.. +,- / *
, . . TrimRight(x), Length(x).
- Group fieIds, .. Average(tile.fieldname, fieldcondition).
, . {@TotaIRecs} .

--
. :

3 69 - - -- - - - - - - - - - --
j
f9 j
@) j .

U :

{orde rs detail. UNI T PRI CE } *. 85

Uppe r Ca s e ({customer .CUSTOMER } )

U :

{c us t ome r . CUSTOMER } [1]

Month ( { orde rs . ORDER } )

U (IF ELSE):
If Remainder (ToNurnber({file .Cus tNum}) , 2 )= Then
{ f il e .O f f e r l }
Else
{ f i l e . Of fer2}

@HARDWARE

If (( {f ile .HardSa!es}5000 ) Then


.0 7 * ({file. HardSales}5000 )
Else

@SOFTWARE

If (( { f i l e . SoftSa!es}lOOOO ) The n
. 10 * {{ fi le. So ftS a l e s } 10 0 00)
El s e

, function DayOfWeek:
I f Not(DayOfWee k({ f i le .Cal l Date in 2 to 6) Then
"Weekend"
Else

U Uu :

' Week # Fl,g ' Week # Fl,g


Sunday 1 Weekend Thursday 5
Mond' y 2 Friday 6
~sday 3 Saturday 7 Weekend

--
Wednesday 4

3 70 - - - - - -- - - - - - - -
:

I f PageNumbe r > 1 Th en
PageNumber
El s e

1 :

Date (1 9 9 0 , 1 0, 1 ) = Oc t 90
! PageNumbe r = 1 Then
Pr intDate
El s e
Da t e ( O, , )

(IF ELSE):
! { f i l e.D e g r e e } <> UPh.D . " and
{ file .Degre e} <> "M.D. " and
{f ile.Degree } <> "0. 0 . S " The n
If { fil e . S e x } = UM" The n
"De ar Mr . + {file. lname }
El se
''De a r Ms. + { file .lname}
El se
''De a r Dr. + {file . lname }

Degree 5. Last Nam. Salutation


. . F Jones "Dear Ms. Jones"
Ph.O. F 5mith "O.arOr. 5mlth"
. . Jackson "O.ar Or. Jackson"
.5 . Miller "Dear Mr. Miller"
0.0.5. F Johnson "Dear D . Johnson "

, :

//

s t r i ngVar Ar eaCod e: = { Cus tomers . Areac o de } [1 to 2 ]


i f a r eac ode = 6 8 t hen
BC
e l se
BW

Reprt : ! Selection formula : Record


(Edit farmula dialag bax), ,

--
:

37 1
{Authors.YearBorn } > 1990 w 1990.
""C" {Authors.Lastname} [1] "C".
{Authors.lName} [1 10 2] = ' " '" .

Vear(Authors.Date) < 1992 1992.

Visual Basic,
, SeIectionFormula, ..:
CrystalReportl. Se lectionFo rmula = " {Autho r s . Aut h or} = 'Adams'"

report
.

CrystfI Reports SUf fsc

' RPT,

.
Crystal Custom Control control
. Tools : Custom Controls Crystal
report control, toolbox.
toolbox controI

r;;.. Test Crystol Reorts &!

E:rirl With API

Printer,S:etup

!:.

. 17.4. TestPrn.vbp.

Crystal Report:
Pr i v a t e Sub CmdPrint-Click()
Di m rpname As String

MousePointe r = 11
Error Re s ume Next

- - - - - - - - - - - -- -
--
372 - - - - - - - - - - - - - -
rpname = App.Pat h & ~ \ "
Cry stalReportl . DataFiles (Q ) = rpname & ~b iblio.mdb"

Crysta lRepo rtl.Destinat ion = Q

\ 1 0 ~o Crystal Reports
Cr ysta l Repo r t l.Re po rt Fi l e Name = rpname & ~Te s t.Rpt
Cry sta lReportl.Action = 1
MousePointe r = Q
End Sub

OJ~

CrystaI Reports (
CRPE32.DLL),
, Database
Iocation, , :
reports.
,
:

Dec lare Fun c tion PEOpenEngine Lib nCRPE3 2 .DLL" () As Inte g er


Decla r e Sub PECloseEngine Lib ~ CRP E3 2 .DL L" ( )
De c l a r e Fu nct i on PECa nClo s e Eng i ne Lib ~ CRPE3 2 . DLL" ( ) As Integer
Declare Funct i o n PEOpenPrintJob Lib ~CRPE 3 2 .DLL" (ByVal RptName$) As
Integer
Dec lare Sub PEClo sePr i nt Job Lib "CRPE3 2 .DLL" (ByVal Print J ob%)
Declar e Fun c ti on PEStartPrintJob Lib "CRPE32 .DLL" ( ByVal Pr intJob%, ByVal
Wa i t OrNot %) As Integer
Dec la r e Sub PECan c elPr intJob Li b "CRPE32. DLL" ( ByVa l Print Job% )
Dec lare Fun cti on PESelectPrinte r Lib "CRPE 32.DLL" ( ByVa l Pr intJob%, ByVal
Print erDr i ve r$, ByVal PrinterName$ , ByVal PortName $, ByVa l DevMo de As Long )
As Inte ger
Decl are Funct i on PEOutputToPrinter Lib ~CRPE32.DLL" ( ByVa l PrintJob% , ByVa l
NCopi e s %) As Int eger
De clare Fun ct i o n PEOutputToWindow Lib ~ CRPE3 2 . D LL " ( ByVal Print Job%, ByVa l
NCopies %) As Intege r

report
50%
CrystaI Custom Control.
Crystal Reports:

Sub CrystalWithAPI ()
Dim result %, j obnum%
Dim Fi l e Loc As String

File Loc App . Path & ", "

r e sul t % PEOpenEngine ( )

--
If r e s ult % = Then

- -- - - - - -- - - - - - - 373 - - - - -- - - - - - - - --
MsgBox RCrysta l Repo r ts Engi ne Op e n Er r or , -,

RUnab le to open Print Eng ine"


Exit Sub
End If

jobnum% = PEOpenPrintJob(FileLoc & Rtes t.RPT")


If j obnum% = Th e n
MsgBox 'rrr report fi le" , - , "Unable t o Op e n Pr int Job"
Exit Sub
End I f
r e s u l t% = PEOutput ToPrinter{ j obnum %, 1)
result% = PEStartPrintJob( jobnum%, Tr ue)
PEClosePrintJob j obnu m%
PECl oseEngine
End Sub

Crystal Reports.

PEOpenEngine Crystal Reporis.


PECloseEngine Crystal Reports.
PEPrintReport = (print - only link).
PEOpenPrintJob .

PEClosePrintJob .

PEStartPrintJob ' .

PEGetJobStatus status .

PECancelPrintJob .

PESelectPrinter .

PEOutputToPrinter .

oWindow .

PEOutputToFile ; .

PEGetFormula .

PESetFormula .

PEGetSelectionFormula .

PESetSelectionFormula .

-'0'- Crystal reports d efaulL~J5.I!Llli1 Windows, '


;.. -, .

-'0"- reports, File Location SI\I\1U~


;.. -, REPORT, template reports
application directory, distribution
.

--
3 74
" ,~_ VERII'Y_ON_E\lERY PRltH ,
-;.. ;. run time errors reports.

,' '~_ l gs reports.


""/ " ;. system directory Windows di stribt ion .

, , ',~_
""/ . ;. , Crystal Reports
PEOpenEngine ( form load )
PECloseEngine ,

- - - - - - - -- - - - -
--
- - 375
5 5C

Visual Basic ' , .


. .
(Application Programming Interface) Windows,
, . (LL) .
OCX, controls,
.
User32, GOl32 Kernel32.
, DecIare
declaration module . , modules
, .
:

De c lare Sub Gl o hn ame Lib "lname" [Al i as "a l i a s narne" ] [( [a rgum ent s] ) ]

Declare Function Globname Lib "lname " [Al i a s name ] [ ( [a rguments] ) ] [As t ype ]

Globname
Visual Basic. 5.0 (
32-bit) 32-bit 4.0
(case sensitive), 16-bit 4.0.
AIias name,
, , '
Globname.
Lib
. Arguments , As Type
Integer, Long, Single, Double, Currency, String ( ) ,
VarIant.
arguments :

[ByVa l ] v a r i able [ As type] [, [By Va l ] variabl e [ As typel ] . . .

--
377

ByVaI by value by reference, defauft


VsuaI Baslc. byvalu. (
) . by reference (user-defined typeS) .

VanabI. VIsuaI Baslc.


As . , : In1eger, Long, Single,
Double, Currency, St g , Variant (user-defined 1Ype). -
Any .

, ,
by value. ,
, :

Dec l are Func tion GetWindows Di rectory Li b ~kerne 1 3 2 n Alias


~Get W i ndows D i recto ryAN ( ByVa l l pBu f fe r AsString, ByVal nS ize As Long ) As Lon g

Pa th= Spa c e$ (255 )


R GetWindowsDi rect ory (Path,
= Len (Path
Path = Left ( Path, R)

GelWindowsDi reclor "" Path


Windows. GelSslemDireclory,
System"
C Long 32-b! Integer
1 6- bt. (handles) Windows (hWnd).
, ,
; ;

# I f Win32 Then
De cla r e Sub Me s s age Be ep Li b "Use r 3 2 " (ByV al As Long )
ffEls e
De c lar e Sub MessageBeep Lib "Use r" ( ByVa l As I nt e g er)
i End If

( ) '
DLL. m , by refemce ( tabs(O)).
DLL,
:

Ty pe RECT
Left As Long
As Long
Right As Long
Bot torn As Lon g
End Type

, DrawFocusRecl ,
. :
De c lare F ucti on Dr a wFo cu sRe ct Li b "user32" Al i a s "DrawFocu s Re c t " ( By Va l

--
hdc As Long , l p Re c t As RECT ) As Long

3 78
by value. , As
, .
, C+ +
32-bit 16-bit Visual Basic:

C++ : 32biI 16-bit (VB4) i


L Long lnteger
char ByVal Byte ByVaI Byte
FARPR OC Long Long
L Long Integer
int Long lnteger
long Long Lo ng
LPSTR ByVal String ByVal String
Pointer 10 a void As Any As Any
WORD Long Integer
short Integer Integer
LL As Any As Any
ByVal Long ByVal Long

/ 32-bit Visual Basic DLL 16-bit,


.

n J W d W 5

Windows (window).
, controls. background desktop .
,
"window proc". ,
Windows . ,
, Windows. , Visual Basic,
:

Function Win dow sP roc &(ByVal hwnd&, ByVal message &, ByVa l wparam& , ByVa l
lpa rarn& )
Se l ect Case message&
Cas e 1i'llLPAIN T
, v Q ~

Case M1..-SETFOCUS
, vQ

End Se lect

, Wi ndows
WindowProc& = De fWindowProc&(hwnd&, mes sage & wparam& , lparam& )
End Func t i o n

--
3 79 - - - - - - - - - - - - - -- -
hwnd
Windows,

( ) .
Windows "window proc"
, , , Message .
WM. , Seiect
Case, .
, .
( )
DefWindowProc. DefWindowProc
"window proc".
Visual Basic 2 SendMessage PostMessage
.
xl box
(read oniy), SendMessage:
Const WM-USER = &4 0 0

Const EMLBETREADONLY = (~USER + 31 )

Dec lare Function Se ndMes s age Lib "user32" Alias "SendMessageA" (ByVa l
h wnd As Long, ByVal wMsg As Lo ng . ByVal wPararn As Lo ng , !Param As Any ) As
Long
SendMessage ( Textl. hWnd. EM.-SETREADONLY , 1, )

napaM pwv (Wdw Crfl55)

(window class)
Windows.
. , ,
. "window proc"
. RegisterClass,
, , WNDCLASS. WNDCLASS :
Type WNDCLASS
sty l e As Long
l p f nwndp ro c As Long
cbClsextra As Lo ng
c bWndExt r a 2 As Long
h l n s t an c e As Long
hlcon As Long
hCur sor As Long
hbrBackground As Long
lpszMenuName As Long
lps zC la ssName As Long

--
End Type

3 8 0 - - - - - -- - - - - -- - - -
10 , .
, (lpfnWndProc) "window
", ' .
style .
, CS mj OR.
, :

wndclass .sty le = CS-HREDRAW Or CS_VREDRAW

, .
, cbClsExtra cbWndExtra
.
(global class) child controls. Windows
7 , :

BUTTON CQMBQBQX LISTBOX MDICLIENT SCROLLBAR STATI C

, :

wnd c la s s. hb r Backgr ound = GetSto ckOb j e c t(WHITE-BRUSH)

, , , IpszMenuName
menu .

p~po

' "
" .
, , ,
. CrealeWindow,
32-bit :
De cl are Function Creat e Wi ndo w Lib "u s e r 3 2" Alias "Creat eWindowA" _
(ByVal lpClassName As St ring, ByVal l pWindowName As String. Byval dwStyl e _
As Lo ng , By Va l As Lon g . ByVal As Lo ng , ByVal nWi dt h As Long, ByVa l _
nHe ight As Long, ByVal hWndPar ent As Long , ByVa l hMenu As Long , _
ByVal h l n s t a n c e As Long, l p Pa ram As Any ) As Lo ng

CreateWindow hWnd HWNO ( Hwnd


Visual Basic), . Windows
. style
. ,
WS OR.
CreateWindow ( ,
"window proc" , WM_CREATE) .
ShowWindow, UpdateWindow
WM]AINT "window prock". Windows
WM_PAINT "window prock", .
UpdateWindow,

--
. Windows -

- - -- - - - - - - -- - - - 381

. ,
hDC (device contet) ,
( video display) .
Windows ( DrawText )
. ( ) ,
(client area) "".
, hardware .

AddressOf
5. 0.
Visual Basic.
module ( )
DLL .
(Enumeration function) ,
Windows. m ,
(fonts) DC ( EnumFonts),
child ' - ( EnumChildWindows),
(proper1i es) ' ( EnumProp),
(tasks) ( EnumTasks) , ,
( EnumWindows).
(callback)
, . Enum.Vbp
EnumWindows, :

Dec la re Func t i o n EnumWi n dows Lib "u s er 3 2" ( ByVa l lpEnumFun c As Long, ByVa l
l Pa ram As Long) As Bo o l e a n

, Long , callback
. ' module
:

EnumWinds (ByVa l wParam As Long, ByVal l Pa r am As Lo ng )

wParam . ,
AddessOf :
lRe t = EnumWi ndo ws (Addres s Of EnumWind s . )

( 18.1.) ListView control (


) .
, , , , hWnd.
Enum.Frm:
, E o o~ 1 n 1 1 EnumWinds
Private Sub Forffi-Load()
Dim lRe t As Lo ng
l Ret = EnumWind ows( Ad dressOf EnumWi nd s , )
Call f i l l

--
End Sub

- - -- - - - - - - -- - - - 382
Pr ivate Su b Fo rm-Re s i z e ( )
Loca l Er r o r Resume Next
Li s t Vi ew 1. Mo v e , , ScaleWidt h, Sca l eH eight
End Sub

xaaK~a

al1KO . 1 0

aal1K

Fu n ct i on Zt rim( ByVal s t As St ring)


s t = Trim( s t)
i = InStr(s t , Chr $ {O
I f i Then s t = Left ( st , Le n ( s t ) - 1)
Zt r im = s t
End Function

ListView cont r o l

10 Ge t Wi n dowTe xt
GetClassName Vl 0

Private Sub fill( )


Dim c a pt As String, c ls s As St r i ng
Dim itm As ListItem

For = iWnds

c a p t = Space (17 1 ) : c l s s = Spa ce(171 )


GetWindowText hWnd s ( ) , capt , 170
! Len( Tr i m( c a p t)) > 1 Then

GetCl a s s Name hWnd s () , c lss , 170

Set itmx = ListVie wl .List Items. Add ( , Zt r i m( c a p t ) )


i t mx. SubItems (1) Ztrim ( clss)
itmx. Sub I t e ms ( 2) = hWnds (x )
End rf
Next
End Sub

module Enum.Bas, , callback EnumWinds,


EnumWindows:
De cl a r e Func ti on En umWin d ows Lib "user32" ( ByVa l lpEn umFun c As Long, ByVal
l Pa r a m As Long) As Bo ole a n
Dec la re Funct i on GetWin dowTe x t Lib " u se r 3 2" Alias " Ge t Wi n d owTextA" ( By Va l
h wnd As Long, ByVal l p String As String, ByVal cch As Long ) As Lo n g
Declare Func ti on GetClassName Lib "user32 " Alias " Ge t Cl a ssNameA" ( ByVa l
h wnd As Long , ByVal lpC lassName As String, ByVal nMaxCo unt As Long ) As Long

, 11

--
3 83
,
Publ i c hWnds() As Long
Public iWnds As I nteger

callback Ka ~

a EnumWindows .
1 x~ hWnd

1 ~

K K ~o 1 .

~ y ~K hHnds

. .

Sub EnumWinds(ByVal wParam As Long, ByVal lParam As Long)


ReDim Pr es ere hWnds(iWnds + 1) As Lo ng

hWnds{iWnds) = wParam
i Wnds = iWnds + 1
End Sub

, ..
Ij Form1

OOE S _ Wndow
OIeMa8"The<fN/nf.j_
I!!I~ EJ

Fncl F&t
R......
IrioSeek Ewtemion / N ~o
B~ M eter
MSWE B~S_
~~
History
VINCII Ba:ic 800. O*le
V~uaI Basic:: Bock $ O*le
" ;10
F~e
MiclmofI\Iord vb5
PIogram Marage

. 18.1. l istView control .

AddressOf
Windows, Subclass Superclass, controls (
) ] .
textbox control .

Windows
control textbox control
. . textbox controls ,
"window proc", Windows .
. GelWindowLong,
GWL_WNDPROC, "window proc" .
SetWindowLong
. . "window proc"
textbox cantrol.
Hook.Vbp . textbox control

--
commandbutton controls. "window proc" textbox control,

3 84
WM_CHAR Windaws.
"window proc" control.
. Hook.Frm:

gHW l l

t e xthox control .

Private Sub Form-Load ( )


gHW = Me. Text l. hwnd
End Sub

Private Sub Commandl_Click( )


Hook
End Sub

Private Sub Command2_Click()


Unhook
End Sub

moduleHook.Bas, "window proc":


Declare Function CallWindowProc Li b "user32" Alias "Ca l l Wi n dowPr o cA " (ByVal
lpPrevWndFunc As Long , ByVal hwn d As Long, ByVal Msg As Long, ByVa! wPa r am
As Long, By Va l lParam As Long) As Long
Declare Funct ion SetWindowLong Lib "user32" Alias "S e t Wi n do wLo ng A" ( By Va l
hwnd As Long, ByVal n lndex As Long, ByVal dwNewLong As Long) As Long

Const GWL-WNDPROC = -4
Const WM-CHAR = &2

Global lpPrevWndProc As Long


Global gHW As Long

"window proc"

y ~ ~x2

gHW. lpPrev WndProc ~x~

~ "wi ndow p roc" .

Public Sub Hook()


lpPrevWndProc = SetWindowLong (gHW. GWL-WNDPROC,
AddressOf WindowProc )
End Sub

, E ~ ~

Public Su b Unhook ( )
Dim temp As Long
t emp = S e tWi ndo wLo ng ( g HW, GWL-WNDPROC, lpPrevWndProc)
End Sub

"window proc " .

Eyx~ WM-CHAR K~ 2~ ~ -1
' ~~

--
l

3 8 5 - - - - -- - - - - - - - - -
, ~ Cal lWindowPro c.

Fun ction WindowProc{ByVal hw As Long . ByVal uMsg As Long, ByVal wPa r am As


Long, ByVal lParam As Long) As Long

Se lect Ca se uMs g
Ca s e WM...-CHAR
! Not IsNumeric (Ch r$ (wParam Then
Beep: windowProc = -1 : Exit Funct ion
End !
Case Els e
End Select
\ l
\ "window p ro c"
Windo wProc = CallWindowProc(lpPrevWndProc, hw, uMsg, wParam. lParam )
End Func t i on

Shell
Visual Basic Shell, .
, ,
CreateProcess
.
WaitForSingleObjec!
.
Shel132.vbp. , , ExecCmd,
:

Private Type STARTUPINFO


cb As Lon g
lpReserved As String
lpDesktop As St r ing
lpTitle As String
dwX As Long
dwY As Lon g
dwXSi ze As Long
dwYSize As Long
dwXCoun t Chars As Long
dwYCountChars As Long
dwFi llAttribute As Long
dwFlags As Long
wShowwi ndow As Integer

--
cbRese rved2 As !nteger

3 8 6 - - - -- - - - - - - - - - -
lpReserved2 As Long
hStdlnput As Long
hStdOutput As Long
hStdError As Long
End Type

Private Type PROCESS_INFORMATION


hProcess As Long

hThread As Long
dwProcessID As Long
dwThreadID As Lon g
End Type

Private Declare Function WaitForSingleObject Lib ukerne132" (ByVal _


hHand1e As Long, ByVa1 dwMi lliseconds As Long) As Long

Private Dec1are Funct ion CreateProcessA Lib ukerne132" ( ByVa l


1p Ap p 1 i c a t i o n Name As Long, ByVal lpCommandLine As String, ByVa 1
l p Pr o c e s s At t r i b u t e s As Long, ByVa l lpThreadAttributes As Long, _
ByVal blnheritHand1es As Long, ByVa1 dwCreationFlags As Lo n g , _
ByVa1 l p Env i r o nme n t As Long, ByVal 1pCurrentDirectory As Lon g , _
lpStartup lnfo As STARTUPINFO, lpProcesslnformation As _
PROCESS_INFORMATION) As Long

Private Dec1are Function CloseHand1e Lib ukerne132" (ByVa1 _


hObject As Long) As Long

Private Const NORMAL-PRIORITY_CLASS &20&

Private Const I NFINI TE = - 1 &

Public Sub ExecCmd(cmd1ine$)


Dim proc As PROCESS_INFORMATION
Dim s tart As STARTUPINFO

start.cb = Len(start)
,
ret& = CreateProcessA( 0&, cmdline$, 0&, 0&, 1&,
NORMAL-PRIORITY_CLASS, 0&, 0 &, start, proc)

l l li

ret& WaitForSing1eObject (proc. hProcess, )

ret& CloseHandle(proc.hProcess)
End Sub

Private Sub Command1_C lick()


ExecCmd Unotepad.exe"
MsgBox uH "
End Sub

--
3 87

ReadlNI$ Wr~elN I .
$ ,
. Sec~ons, Keys .
:

(Section]
ke=au e

De c l ar at ions s tandard modul e


Declare Function WritePrivateProfile St ring Lib ~kerne13 2u
Alia s "WritePrivateProfileStringA"
ByVal lpA pplicationName As String, ByVal lpKeyName As Any,
ByVal lpString As Any , ByVal lpFileName As String) As Long
De cla re Function Get Pr i vate Pro fi l e String Lib "ke rne132" Alias
"GetP riat e P ro f i le S tri ngA - (ByVal lpApplicat ionNarne As String , ByVal
n

l pKeyName As Any, ByVal lpDefault As St ring.


ByVal l pReturnedString As String, ByVa l nSi ze As Long , ByVa l lpFileName
As String ) As Long

Funct ion Re a dI NI $ (App$ , Sect ion $, Key $ )


MaxSize = 512
a$ Spa ce $( Max Si ze)
=
jGetPr ivateProf ileString( Se ction$ , Key$ , " " , a $, MaxSiz e ,
= $ )

a$ ~ Trim$(a$): a$ = Left$ (a$ , Len(a$ ) - 1)


ReadI NI $ = Tr i rn$ ( a $ )
End Function

! :

a $ : Left$ (a$, Len (a $ ) - 1)

. C (
C), ASCII
. , Visual asc .

System Menu
Visual Basic System ( Control
) ,
KillSystemMenultem . System n
( ) . .
4 , Minimize.
hWnd
.

, Dec la rations
De c la re Function GetSysternMenu Lib U us e r 32" Alias uGetSystemMenu" (ByVal
hwnd As Long, ByVal bRev e rt As Long) As Long
Dec l are Function RernoveMenu Lib ~ u s e r 3 2 " Alias ~ RernoveMenu N (ByVal hMenu

--
3 88 - - - -- - - - - - -- - - -
As Long, ByVal nPosition As Long , ByVal wFlags As Long) As
Long

Sub Form......Load ()
Call Kill Sy sternMenuItem(4 )
End Sub
Sub Kil l SysternMenuItem ( i As Intege r )
Cons t MF-BYPOSITION = & 400
HSysMenu = GetSy stemMe nu (Forml .hWnd, )
k = RemoveMenu (HSysMenu, i , MF-BYPOSITION)
End Sub



. GetTempFileName
Temp
Windows. GetTmpFile$ .
. DLL,
, ' .
Space$. ,
. , Left$
.

, Decl a rations standard module


Declare Function GetTempFi l e Name Lib *kerne 132 Alia s *Ge tT empFi l eNameA
N N

(ByVal lpszPat h As String, ByVal lpPref ixSt r ing As St r i ng , ByVal wUnique


As Long, ByVal lpTempFileName As St r i ng ) As Long
De c l are Functlon GetTempPath Lib "ke rne 132" Al ias "GetTempPathA" (ByVa l
nBufferLength As Long, ByVal lpBuffer As String ) As Long
Func t i on GetTmpf ile$()
Dim i As Long
Path$ = Spa ce $( 2 55) : i = GetTempPath( 25 5, Path$)
f ile$ = Space$( 2 55) : i = Get TernpFi leName (Tr im$ (Path$) , *VD'', , fi l e $ )
= InStr(file $, Chr$ (O : If Then fil e$ = Left $ (file$ , - 1)

GetTmpfile $ = fil e $
End Funct i on

Program Manager
, Program Manager Windows 95. m
, , .
Run Windows Progman.
Program Manager; ,
FindWindow ,
.
( hWnd) . U Pointers ( As Any)
(ByVal 0&) L:

\ Declarations

--
3 89 - -- - - - - - - - - -- - - -
Pri v ate Dec lare Funct ion FindWindow Lib ~u se r32" Alia s
~ F i ndW i ndowA "

( ByVa l l pClas sName As Any, ByVal lpWindowName As Any ) As Long


P r ivat e Decla re Funct ion Se t Wi n d owText Lib ~ u s e r 3 2 " Alias
~Se tWindo w Text A"

( By Va l hwnd As Long, ByVal l pString As String ) As Long

Su b F orLLoa d ()

Di m hwn d As Integ e r

hwnd = Fi ndWindow(ByVal 0&, ~Program Manag er ")


! hwnd = Th en Ex it Sub
Call SetWi ndowTe xt (hwnd, ~New Title" )
En d Su b

hWnd
FindWindow :

hWnd = FindWindow(ClassName $ , 0 &)

, , .


,
(always on ). SetWindowPos.
, Command1_Cl ck
, Command2_Clck .
, Declarations st a nda rd modu le
Declare Su b SetWindowPos Lib ~user32" Alias ~ S et W i ndowP os " ( ByVa l
hwn d As Long, ByVal hWndlns ertAfter As Long, ByVal As Long, ByVal
As Lo n g, ByVa l cx As Long, ByVal cy As Lo ng, ByVal wFl a g s As Long )

Sub CommandL-Click ()
SetWindowPos formI. hWnd, -1, , , , , & 5 0
End Sub

Su b Command2_Cl ick ()
Set Wi n d owPo s formI. hWnd, -2, , , , , &50
En d Sub

Recycle
,
ShellDelete , Win32
SHFileOperalion,
Recycle Bin . ParamArray
. main
32-bit Visual Basic. ,
SHFileOperatIon, , wFunc,
, , .

Option Expl ic it
Type SHFILEOPSTRUCT

--
3 9 0 - - - - -- - - - - - - - - - -
hwnd As Long
wFunc As Long
pFrom As String
As String

fFlags As Integer
fnyOperationsAborted As Boolean
hNameMappings As Long
lpszProgressTitle As String ' FOF-SIMPLEPROGRESS
End Type
,
Public Const FO_COPY "" &2 YlQ l
Public Const FO-DELETE = &3
,

YlQ l
Public Const
, YlQ
FO---MOVE "" &
Public Const
,
FO--RENAME "" &4 YlQ

Public Const FOF-ALLOWUNDO "" &40

Declare Function SHFileOperation Lib u shel132.dll" Alias


uSHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

Public Function ShellDelete(ParamArray Filename() As Variant) As Long


Dim As Integer
Dim sFilenames As String
Dim SHFi leOp As SHFILEOPSTRUCT

For = LBound(Filename) UBound (Filename)


If Dir$(Filename(I) ) <> U" Then
sFilenames = sFilenames + Filename(I) + vbNullChar
End If
Next
sFilenames = sFilenames + vbNullChar

SHFi leOp.wFunc = FO-DELETE


SHFileOp.pFrorn "" sFilenames
SHFi leOp. fFlags "" FOF-ALLOWUNDO
ShellDelete "" SHFileOperation(SHFileOp )
End Function

Sub main()
Dim lResult
ReDim sFileName(l 3) As String

, l

lResult"" ShellDelete(U c:\ga ia\download\wl08C-32. zip")

, l a

sFileName(l) uFirst"
sFileName(2) uSecond"
sFileName (3) uThird"
lResult = ShellDelete(sFileName())

\ l l
lResult = ShellDelete (UFirst" r uSecond" r UThird")

--
End Sub

3 91
Formal
u Win32 , u
Visual Basic.
Format.Vbp command buttons
DriveLlstBox u Drive, u
. u SHFormaIDrive. format
u. u u :

Private De c l a r e Functi on SHFormatDr ive Li b ~she l 1 3 2" (ByVal hwnd As Long ,


ByVal Drive As Long, ByVal f mtID As Long, ByVal opt ions As Long) As
Long
Private Dec l are Funct i on GetDriveType Lib ~kerne 13 2" Al i as ~ GetDrive T ypeA" _
(ByVal nDrive As String) As Long

a f rma t ~K

Priv at e Sub Comma ndl_ Click ( )


Di m Drive Lett er$, Dr i veNumber&, Dr i ve Type&
Di m Re t Va l&, RetFromMsg %

Driv eLe t te r= UCa s e (Dr i v e l.D r i v e )


\ l . =

DrieNumbe r = (Asc(DriveLetter) - 65): DriveType Ge tD riv e Typ e (Dr i


eLetter)

I f Dr i ve Typ e = 2 Then ' Flopp i e s


RetVal = SHFo rma t Dr i ve( Me.hwnd, DriveNumber, 0 &. 0&)
End I f
End Sub
, v ~ ~ K

Pri vate Sub Command2_Cl i c k ( )


Dim Dr iveLetter$, DriveNumbe r&, DriveType&
Dim Ret Val&. RetFromMsg&
Driv eLette r = UCas e (Driv el.Dri v e )
, ~ . =
DriveNumber = (Asc(DriveLetter) - 65): DriveType Get Dr i veType( Dri ve Let ter)

If DriveType = 2 Then ' Floppie s


, Di s kCopyRunDll x~
, - From K~
Re tVa l = Shell ("rundl132.exe " & " diskc opy. d l l. " _
& "Di s kCop yRunDll \\ & Dr iveNumber & " ," & Dr i ve Numbe r . 1)

Else
RetFrornMsg = MsgBox ( " f l oppies " & " " , 64, _
"Dis kCopy Exampl e")
End If
End Sub

--
3 92
, E~o ~ou Dr ive

Pri vate Sub DriveL-Cha nge ( )


Dim Dr iveLe t ter$ , Drive Number &, Dr iveType &
DriveLetter = UCa se (Dr i ve l .D r ive ): Dr iveNumber (As c( DriveLetter) - 65 )
Dr iveType = GetDriveType(Drive Let ter)
! DriveType <> 2 The n ' Floppies

Cornmandl.Enabled False: Command2. Enabled = Fa lse


Else
Commandl .Enab led True : Comrnand2.Enabled = True
End If
End Sub


,
GontrolBox.
ChangeSlyleBiI, ,
iHwnd, ui]
( VB) . afNew ,
f , True False :

Declare Func t i on Ge t Wi ndowLong Lib ~ u s e r 3 2 " Alias ~Ge tWi ndowLongA n (ByVa l
hwnd As Long. ByVa l nlndex As Long) As Long
Decl a re Function SetWi ndowLong Li b "us e r 32" Alias "SetWindowLongA" (ByVal
hwnd As Lon g, ByVal n lndex As Long, ByVal dwNe wLong As Long ) As Long
De c l a r e Fun ction SetWi ndowPos Lib "use r 32" Al i a s "SetWindowPos " (ByVal
hwnd As Long , ByVal hWndlnsertAfte r As Long, ByVal As Long, ByVal As
Long, ByVal c x As Long, ByVal cy As Long. ByVal wFl ags As Long) As Long
Sub Cha ngeSt yleBit (iHwnd As Long , f As Boolean. afNew As Long )
Dim af As Long
! iHwnd = Then Exit Sub
a f = GetWi ndo wLong ( i Hwnd, GWL-S TYLE)
I f f Then
af af Or a fNe w
Els e
af af And (Not afNew )
End !
Cal l SetWindowLong (iHwnd, GWL-STYLE. af )
Call SetWindowPos (iHwnd, HWND-NOTOPMOST, . , . , _
SWP-NOZORDER Or SWP-NOSIZE Or SWP-NOMOVE Or SWP-DRAWFRAME )
End Sub

Timer
Timer Visual
Basic. .

Declare Function timeGetTime Lib "wimnm. dll" Al i a s ~timeGetTirne" () As Long

Function Tirner{ ) As Single

--
3 93
Timer = timeGetTime / 10 00 !
End Funct ion

' listbox control


Visual Basic '
listbox control,
control. S etLstHo r , ,
Load , :

Dec la re Function SendMessage Lib "us er32 H Alias " Se ndMe s s ageA" (ByVal hwnd
As Long, ByVal wMs g As Long, ByVal wPararn As Lon g, lPararn As Long ) As Long
Sub SetListHor( Li s t 1 As Li s t Box )
Const WM-USER = &400
Cons t LB-S ETHORI ZONTALEXTENT = (WM-USER + 21 )
SendMessage List1.hwnd, LB-SETHORIZONTALEXTENT, CIntListl.Width * 2 ) /
Screen.TwipsPerPixelX ),
End Sub

ShExecute - Shell
ShExecute ,
, ,
. , Dac1.Doc,
Word. ,
ShellExecute.
De c l a r e Functi on ShellExecute Lib " shel132 . d l l H Al i a s "ShellExecut eA H
(ByVa l hwnd As Long , ByVal lpOpe r a t i on As String, ByVal l pFi l e As St r i ng,
ByVal l pPa rarnete rs As String. ByVa l l pDi r e c t o r y As Stri ng , ByVal nSh owCmd
As Long ) As Long
Fun ction ShExe cute ( iF ile As String) As Integer
Cons t SW-SHOW = 5
If Dir$ (iFile) <> . Then Exi t Func t i on
ShExe c ut e = Shell Execut e (O&, vbNullSt r i ng, iF i le,
vbNullSt r i ng , vbNul l St ring, SW-SHOW)
End Fun ction


Taskbar
Tbicon.Vbp ,
taskbar Windows 95 '
' . , taskbar
, picturebox control .
MouseMove .
:

Opt ion Explicit


Private Type NOTIFYICONDATA
cbSize As Long

- -- - - - - -- - - - - --
--
39-4
hWnd As Long
uld As Long
uFlags As Long
ucallbackMessage As Long
h lcon As Long
szTip As String * 64
End Type

Private Const NIM......ADD = &


Privat e Const NI M...MODI FY = &
Pr ivate Const NIMJ>ELETE = &2
Private Const WM....MOUSEMOVE = &2 00
Private Const NIF---ME SSAGE = &
Private Const NIF_ICON = &2
Private Co n s t NIF_TIP = &4

Private Const WH-LBUTTONDBLCLK = &203


Private Const WH-LBUTTONDOWN = &201
Private Const WM.....LBUTTONUP = & 202
Private Const WMLRBUTTONDBLCLK = &206
Private Const WMLRBUTTONDOWN = &204
Private Co nst WMLRBUTTONUP = &205

Private Declare Function Shell-Notifylcon Lib ~shel132" Al ias


~Shell-NotifylconA" (ByVa l d wMessage As Long, pnid As NOTIFYICONDATA ) As

Dim t As NOTIFYICONDATA

, t

, NOTIFYICONDATA
Private Sub Fo rffi-Load()
t .chSize = Le(t )
t.hWnd = pichook.hWnd
t.uld = 1&
t .uFlags = NIF_ICON Or NIF_TIP Or NIF---MESSAGE
t.ucallbackMessage = WM....MOUSEMOVE
t.hlcon = Me.lcon
t . szTip = ~Shell-Notifylco. .. " & Chr$ (O )
Shell-Notifylcon NIM-ADD. t
Me.Hide
App.TaskVisible = Fa lse
End Sub

\ in Click
\

Private Sub mnuMain-Click (Index As I n t e g e r )


Unload Me
End Suh

taskbar.

--
39 5
Pr i v at e Sub pichoo1L.MouseMove (8 utton As In tege r . Shift As
In tege r , As Si ng le, As Single )

Static re c As 8oo1e an. msg As Long


msg = / Scre e n. TwipsPerP i xe lX
I f re c = Fal s e Then
re c = True
Se lect Ca s e msg
Ca s e WM......LBUTTONDBLCLK:
Msg80x ~D oub l e cl ick ! W
Cas e WM......LBUTTONDOWN:
Cas e WM......LBUTTONUP:
Cas e WM......RBUTTONDBLCLK:
Cas e WM......RBUTTONDOWN:
Ca s e WH-RBUTTONUP :
Me . PopupMe nu mnuBa r
End Select
re c = Fa lse
End I f
End Sub

Iistbox conlrol
Iistbox ( combo box) controI

LockWindowUpdate, :

Declare Functio n Loc kWi ndowUpdat e Lib ~ u s e r 3 2" Alias "Lo ckWindowUpdate"
( ByVal hwndLoc k As Long ) As Long

Dim i %

Lo c kWi ndowUpdat e List l .hWnd


Fo r i % = 1 to 1000
Li s t1. AddI t e m St r $ ( i%)
DoEvents
Next
Lo ckWindowUpdat e 0&

lext boxes conlrols


text box
(read ), SendMessage.
Const WM-USER = &4 0 0
Const EMLSETREADONLY = (WH-USER + 3 1 )

Declare Func t i on Se ndMe s sag e Lib ~ use r32 w Al i a s ~SendMessageA (ByVal


hwnd As Long . ByVal wMs g As Long . ByVal wPa ram As Long, lParam As Any) As
Long

Se ndMessage (Te xt1.hWnd. EMLSETREADONLY. 1, )

--
3 96 - - - - - - - - - -- - - ---
multiline text baxes cantrals
SendMessage,
multiline text boxes controls, Visual Basic
.
multiline text box control:
Function ScrollText& (TextBox As Control, vLines As Integer, hLines As
Integer)
Const EM-LINESCROLL = &406

lines& = CLng(&HI0000 * hLines) + vLines


Success& = SendMessage(TextBox.hWnd. EM-LINESCROLL, , l ines&)
ScrollText& = Success&
End Function

GetLineCount
multiline text box control:
Function GetLineCount (TextBox As Control)
Const EM-GETLlNECOUNT = &400 + 10

GetLineCount = SendMessage(TextBox.hWnd, EM-GETLINECOUNT, 0&, 0&)


End Function

GetCetLe caret (
) text box:
Function GetCurrentLine (TextBox As TextBox)
Const EM-LINEFROMCHAR = &400 + 25

GetCurrentLine = SendMessage(TextBox.hWnd. EM-LINEFROMCHAR. - 1, 0&)


End Function

LineLength . CharPos
lndex . -1,
:

Function LineLength (TextBox As TextBox, CharPos As Long)


Const EM-LINELENGTH = &400 + 17

LineLength = SendMessage(TextBox.hWn~ EM-LlNELENGTH, CharPos, 0&)


End Function

ReplaceSel
Bufter$:
Function ReplaceSel (TextBox As TextBox, Buffer$)
Const EM-REPLACESEL = &400 + 18

ReplaceSel = SendMessage{TextBox.hWnd, EM-REPLACESEL, 0&, Buffer$)


End Function

--
3 97
Undo
tetbox control:
Funct ion Undo (TextBox As Te xtBo x )
Const WH-USER = &4 0 0

Co n s t EM-UNDO = WM-USER + 23

Undo = SendMessage(TextBox.hWnd, -D . , 0 &)


End Funct ion

, " "
tet box s$ en$:
Sub i nsert-char(st$, en$)
Const WMLPASTE = & 3 02

temp$ = Clipboard. GetText


Clipboard. Clear
Clipboard.SetText st + text l.SelText + en$
Se ndMe s s a g e textl .hwnd, WMLPASTE, ,
Cl ipboa rd.SetText temp$
textl.SetFocus
End Sub

Tetlnse rtLine, , Linelndex ,


LineNum , !t:

Sub Text lnsertLine(TextBox As Te xtBo x , txt As St r ing, Li ne Num As Long)


TextBox.Se lStart = Linelndex(TextBox, Li n e Num)
TextBox.SelText = txt + vbCrLf
End Sub

, Vlewer
Visual Basic.

1. GetSystemDirectory,
System Windows.

2. FindWindow, GetWindow GetWindowText,


tet box control .

3. GetSystemMetrics, .

4. DISKSPACEINFO GetDiskFreeSpace,
, bytes,

- - - - - - - - -- - - - - -
--
398 - -- - - - - - -- - - - - -
..
' .

5.
. GetComputerName.
.

6. 32-bt, Gaia32.DLL.
, Compress & Decompress,
. :

De c l a r e Funct i on Compress Lib ~Gaia32.DLLW ( ByVa l source$ , ByVal target$)


As Long

De clare Func tio n DeCompres s Lib ~Ga ia32 .D LLW (ByVa l source$ , ByVal tar -
getS)
As Long

. .
Compress,
( ) .
, DeCompress,
.
, (PKUNZIP) .

- - - - -- - - - -- - -- -
--
399 - - - -- - -- - - -- - --
Collections 35, 295
ComboBox Control 155
Command button Control 7
ljI ActlveControl 214 Command$ 44
r. ActiveForm 56 CommonOialog Control 170
ActiveX Controls 319 Const 31
ActiveX LL 19 CreateOatabase 261
ActiveX Oocuments 335 CreateField 268
ActiveX 19 Createlndex 268
ActiveX Interlace Control Wizard 322 CreateObject 305
AddNew 235, 279 CreateProcess 386
AddressOI 382 CreateOueryOel 265
Aggregate Functions 284 CreateRelation 265
opoi 26 CreateTableOef 266
Ambient 327 CreateWindow 381
And 27 CreateWorkspace 259
Animation Control 195 Crystal Reports 367
377 Currency 28
69
Append 55
252
Oata Control 232
AppendChunk 271
Oatabase 262
Arrange 89
OataField 233
Array 34
OataGrid 176
Asserts 63
OataObjecf 130,132
AsyncRead 329
OataSource 232
AutoRedraw 95
Oate 28,47
r: Bi 249 OateSerial 47
.: BOF 236 Oay 47
BookMmark 236 Grid Control 244
Boolean 28 OBEngine 25
Bound Controls 243 216
Reference 38 Oebugging 60
Byte 28 Oellnt 30
ByVal 38 Oeftype 28
OefWindowProc 380
~ Caption 10
: CCur 32
Oim 28,33
71
oi 37
OirecIory List 161
CheckBox Contol 152
00 52
Checked 78
OoEvents 49
Circle 100
34
Class Module 295
Oouble 28
Clipboal 213
Orag-and-Orop 122
Clone 279
OragMode 123

--
Cls 54

4 01
OrawFocusRect 378 GetWindowsOirectoty 378
OrawMode 103 GoTo 52
OrawStyle 102
O rawTet 382 I I HdC 382
OrawWidth 96 l 355
List 160 54

D Early Bound

303
239
Hour

47
332
348
Enabled 78 HyperLink 328
EndOoc 11
Enum
Enums
326
35 11 :~age Control
ImageLlis! Control
50
164
185
EOF 236
Erase 34 Implements 302
Err 62 Indexes 251
62 Input 56
Event 298 Input$ 56
Eto O 327 InputBax 29

11 Field
Field
269
269
InputBox$
Instancing
29,49
296
Instr 45
File List 162 Integer 28
FileCopy 59 Internet l 311
FillColor 102 IntemetTransfer Control 347
F111Style 103 IsArray 30
FindWindow 389 IsOate 30
Font 107 IsNu11 30
FontTransparent 107 IsNumeric 29
For 53 IsObject 30
For Each
Forrn Module
53
17 13 Keyboard
KeyPreView
143
143
Forrnat 46
293
Frame Control 149
FreeFile 55 Kiil 64
Fdend 297 D l abelControl 150

m
FTP 351 Late Bound 304
GetChunk 272 LBound 34
GetOata 130 Lcase 46
GetFormat 130 l eft 45
GetSettIng 71 Len 45
GetSystemOirectory 378 Line 98
GetTempFile 389 Line Control 168
GetTet 213 Line Inpu! 56
GetWindowLong 384 ListBox Control 153

--
Listview Control 186

...02
Base 33
LockWindowUpdate 396
Lof 59 Option l 30
Long Integer 28 Optional 43
OptionButton Control 151
lJ Main
upo 48
Or 27
44
BV 284
87
Menu

Methods
75
23
54
m OufPuf

P-code
Page
55

13
111
Microsoft Mail 181 Painf 95
Mid 45 PaintPicture 1
47 ParamArray 43
Modal 54 Parameter 275
Modeless 54 Parent 138
Month 47 PictureBox Contol 166
Mouse 11 9 n l 32
Mouselcon 127 99
MousePolnter 127 Polymorphism 302
MS AexGrid C o ntol 197 PopupMenu 79
MS Word 307 PostMessage 380
MSChart Contol 176 Prevlnstance 69
MSComm Conto l 178 Primary Key 232
MsgBox 29, 48 Primary Key 251
Multimedia Control 196 107

m NewPage
NoMatch
!
11
238
27
PrintForm
Private
Program Manager
11
31
223
ProgressBar Contol 184
Now 47
Projects

m
17
Object 293 PropBag 323
Objecf Variables 36 Property Procedures 40
OOBCOirect 253 PropertyChanged 323
L 226 Pset 97
LAufomation S ere rs 304 Public 31
L Orag And Orop 128 Puf 57
OLEOrag 132
OLEOra9Drop 130 ! QueryDet 274

OLEOragOver 130
OLESetData
OLEStartDrag
133
132
11 RalseEvent
RalseEvents
298
37
Error 61 Read 55
55 ReadPropertles 323
OpenDatabase 262 Record 231
OpenRecordSet 263 RecordSet 235, 276

--
- 403
RecordSource 234 Structures 34
Recycle 390 , 39
Redim Pre sere
RegisterClass
34
380 D Table
TableOef
231
267
RegisterRoutIne 362
abStrp Control 195-
RegSvr32 169
C 338
Rem 25
24
Resume 61
26
RGB 97
xt 10
RichTextBox Control 188
xt Control 5
Right 45
TextHeight 108
Rnd 63
TetWidth 108
37
Then 50

t SaveSetting 71 Time 47
Scale 96 TimerControl 163
ScaleMode 96 TimeS eal 47
Scroll Bars 157 oolBar Control 188
Second 47 Transactions 242
Seek 57,282 TreeView Control 193
Selec! 51 m 46
SendKeys 146 34

SendMessage 380 , 28
SetAttr 162
SetFocus 54 ! UBound 34
.SetText 21 3 Ucase 46
SetWindowLong 384 Update 235
S eWin d owPos 390 UpdateControls 242
Shape Control 167 UpdateRecord 242
Shell 386 U pd ateWnd ow 381
S hell Eec ute 394' UserMode 327
SFnmat e 392
! aa 28
Show 54
Vartype 28
ShowWnd ow 381
Sc ! 335
Single 28
Slider Control 184 !!J WebBrowser ControI 312
Sockets 339 WeekOay 47
Space 45 While 52
Speil Checker 311 Wincosk Control 339
SQL 283 WinHeIp 364
SSTab Control 181 WithEvents 37, 299
Standard Module 18 Worl<Space 260
Static 31 We 55
StatusBar ControI
Str$
183
45
m Wte P roper1ies

Year
323

47

--
Strng 28, 45

.. ..

You might also like