UNIVERSITETI “PLANETARI TIRANËS” PROGRAMIM OBJECT - ORIENTED Pregatiti: Nevila XOXA
UNIVERSITETI “PLANETARI TIRANËS”
PROGRAMIM
OBJECT - ORIENTED
Pregatiti: Nevila XOXA
Tabela e përmbajtjes
1. Gjuhët e programimit..........................................................................................................................2
Gjuha e makinës......................................................................................................................................2
Gjuha assembler......................................................................................................................................2
Gjuhët e nivelit të lartë............................................................................................................................2
2. Gjuha Visual Basic. Hyrje ne gjuhen e programimit Visual Basic dhe mjedisin e tij.............................2
Objektivat e kursit...................................................................................................................................2
Çfare eshte Visual Basic?.........................................................................................................................2
Disa vecori te Visual Basic........................................................................................................................2
Struktura e nje aplikimi ne Visual Basic...................................................................................................2
Hapat e zhvillimit te nje Aplikimi.............................................................................................................2
Vizatimi i nderfaqes se perdoruesit dhe vendosja e vetive..................................................................2
Percaktimi i vetive te objekteve ne momentin e dizenjimit (Design Time)..........................................2
Vendosja e vetive gjate ekzekutimit te programit (Run Time).............................................................2
Variablat..................................................................................................................................................2
Tipet e te dhenave ne Visual Basic.......................................................................................................2
Deklarimi i Variablave..........................................................................................................................2
3. Gjuha Visual Basic. Instruksione dhe shprehjet në Visual Basic...........................................................2
Një histori e shkurtër e Basic...................................................................................................................2
Instruksione dhe shprehjet në Visual Basic.............................................................................................2
Operatorët e Visual Basic....................................................................................................................2
Funksionet e Visual Basic.........................................................................................................................2
Konstantet simbolike të Visual Basic.......................................................................................................2
Instruksionet e degëzuara në Visual Basic – instruksioni If......................................................................2
Kontrolli i Tastave të shtypura.................................................................................................................2
Select Case – Një tjetër instruksion i degëzuar........................................................................................2
Instruksioni GoTo.....................................................................................................................................2
Programim object-oriented Faqa 2
Ciklet në Visual Basic...............................................................................................................................2
4. Gjuha Visual Basic. Eksplorimi i kontrolleve të Toolbox –it të Visual Basic..........................................2
Dritarja e mesazhit (Message Box)..........................................................................................................2
Metodat...................................................................................................................................................2
Objekti Form............................................................................................................................................2
Kontrolli Command Button......................................................................................................................2
Kontrolli Label Boxe.................................................................................................................................2
Text Boxes...............................................................................................................................................2
Check Box-et............................................................................................................................................2
Option Buttons........................................................................................................................................2
Vektorët...................................................................................................................................................2
Vektorët e kontrolleve.............................................................................................................................2
Frame-t....................................................................................................................................................2
List Box-et................................................................................................................................................2
Combo Box-et..........................................................................................................................................2
5. Gjuha Visual Basic 6.0. Eksplorimi i kontrolleve të Toolbox –it të Visual Basic (vazhdim)....................2
Shtesat përbërëse të një forms-i (Display Layers)...................................................................................2
Kontrolli Line...........................................................................................................................................2
Kontrolli Shape........................................................................................................................................2
Scroll bar (Ashensorët Horizontalë dhe Vertikalë)...................................................................................2
Kontrolli Picture Box................................................................................................................................2
Kontrolli Image Box.................................................................................................................................2
Kontrolli Drive List Box.............................................................................................................................2
Kontrolli Directory List Box......................................................................................................................2
Kontrolli File List Box...............................................................................................................................2
Sinkronizimi i kontrolleve Drive, Directory, dhe File List Boxes...............................................................2
Kontrolli Common Dialog Box..................................................................................................................2
Dritarja Open e kontrollit Common Dialog Box...................................................................................2
Dritarja Save As e kontrollit Common Dialog Box................................................................................2
6. Gjuha Visual Basic. Krijimi i një aplikimi Visual Basic...........................................................................2
Konsiderata për ndërtimin e ndërfaqeve.................................................................................................2
Perdorimi i General Sub Procedures ne Aplikacion................................................................................2
Programim object-oriented Faqa 3
Percaktimi i nje Sub Procedure............................................................................................................2
Thirrja e nje Sub Procedure.................................................................................................................2
Pozicionimi i Sub Procedures...............................................................................................................2
Kalimi i argumentave ne një Sub Procedure........................................................................................2
Perdorimi i General Function ne Aplikacione..........................................................................................2
Percaktimi i nje Funksioni...................................................................................................................2
Thirrja e nje Function..........................................................................................................................2
Pozicionimi i Function Procedures......................................................................................................2
Shtimi i menuve ne nje Aplikacion...........................................................................................................2
Përdorimi i “Package & Deployment Wizard” për krijimin e paketës instaluese.....................................2
7. Identifikuesi i gabimeve, Debugging dhe File Input/Output...............................................................2
8. Aksesimi dhe Menaxhimi i Bazave te te Dhenave................................................................................2
Struktura dhe terminologjia e bazave te te dhenave...............................................................................2
ADO Data Control....................................................................................................................................2
Data Control Properties.......................................................................................................................2
Data Links............................................................................................................................................2
Percaktimi i tabelave...........................................................................................................................2
Data Tools te lidhur (bound)....................................................................................................................2
Vetite e Bound Tool.............................................................................................................................2
Krijimi i nje tabele virtuale.......................................................................................................................2
Gjetja e Regjistrimeve Specifike..............................................................................................................2
Data Manager..........................................................................................................................................2
Menaxhimi i Bazes se te Dhenave (Database Management)...................................................................2
Kontrollet per Informimin e te Dhenave (Custom Data Aware Controls)................................................2
DataList Box.............................................................................................................................................2
DataCombo Box.......................................................................................................................................2
DataGrid Tool..........................................................................................................................................2
Krijimi i Data Report................................................................................................................................2
9. Gjuha Visual Basic. Disa kontrolle te vecuara......................................................................................2
Kontrolli Masked Edit..............................................................................................................................2
Vetite e Masked Edit............................................................................................................................2
Ngjarjet e Masked Edit........................................................................................................................2
Programim object-oriented Faqa 4
Kontrolli Chart.........................................................................................................................................2
Veti te kontrollit Chart Control............................................................................................................2
Kontrolli Multimedia................................................................................................................................2
Programimi i kontrollit Multimedia:....................................................................................................2
Kontrolli Rich Textbox..............................................................................................................................2
Vetite, Ngjarjet dhe Metodat e kontrollit Rich Textbox.......................................................................2
Disa metoda unike te rich textbox jane...............................................................................................2
Kontrolli Slider.........................................................................................................................................2
Vetite e kontrollit Slider:......................................................................................................................2
Kontrolli Tabbed Dialog...........................................................................................................................2
Kontrolli UpDown....................................................................................................................................2
Vetite e kontrollit UpDown..................................................................................................................2
Ngjarjet e kontrollit UpDown...............................................................................................................2
Kontrolli Toolbar......................................................................................................................................2
Perdorimi i Windows Clipboard...............................................................................................................2
Printing with Visual Basic.........................................................................................................................2
Aplikacionet ne Visual Basic me Shume Forma.......................................................................................2
Visual Basic Multiple Document Interface (MDI).....................................................................................2
Design-Time Features of MDI Child Forms:.........................................................................................2
Run-Time Features of MDI Child Forms...............................................................................................2
Creating a Help File..................................................................................................................................2
Creating a Help Text File..........................................................................................................................2
Compiling the Help File........................................................................................................................2
Attaching the Help File........................................................................................................................2
More Help File Topics..........................................................................................................................2
Class Summary.........................................................................................................................................2
Shembulli i fundit....................................................................................................................................2
10. Appendix I. Simbolet e Kontsanteve ne Visual Basic......................................................................2
11. Appendix II. Common Dialog Box Constants..................................................................................2
12. Kodet ASCII....................................................................................................................................2
Kodet 0-127............................................................................................................................................2
Kodet 128-255........................................................................................................................................2
Programim object-oriented Faqa 5
1. Gjuhët e programimit
Nëpërmjet algoritmit paraqitet në një formë “të lirë” zgjidhja e një problemi
të caktuar. Algoritmi nuk lidhet me ndonjë sistem konkret kompjuterik.
Të marrësh rezultate reale duhet që algoritmi të shprehet në gjuhën bazë të
kuptuar drejpërsëdrejti nga kompjuteri.
Gjuha (natyrale) është një mjet komunikimi ndërmjet qënieve njerëzore
(shqip, anglisht , etj). Nëpërmjet gjuhës natyrale nuk mund t’i transmetohen
kompjuterit të dhëna dhe instruksione, ai nuk i kupton (për momentin!).
Prandaj janë krijuar gjuhët e programimit, të zhvilluara posaçërisht, për t’i
transmetuar kompjuterit të dhënat dhe instruksionet për të kryer një detyrë
të caktuar.
Instruksionet që i duhen dhënë kompjuterit për
zgjidhjen e një problemi apo për realizimin e një
detyre duhet të shkruhet në një gjuhë të vecantë të
quajtur gjuhë programimi.
Përmendim disa prej tyre në rendin historik: Asambler, Fortran, Cobol, Basic,
Pascal, C, C++, Java, Visual Basic.
Gjuhët programimi shërbejnë si ndërmjetës për zbatimin e një algoritmi në
kompjuter. Megjithëse ekzistojnë me qindra gjuhë programimi, ato të gjitha
klasifikohen në kategoritë si më poshtë:
1. Gjuhët e nivelit të ulët
a. Gjuha e makinës (machine language)
b. Gjuha assembler (assembly language)
Programim object-oriented Faqa 6
2. Gjuhët e nivelit të lartë
Gjuha e makinës
Gjuha e makinës është gjuha e vetme që kuptohet drejtpërsëdrejti nga
procesori i kompjuterit. Quhet edhe kod makine (machine code) dhe
shprehet si varg 0 (zerosh) dhe 1 (njëshash). Kur ky varg kodesh futet në
kompjuter, procesori i njeh ato dhe i kthen në sinjale elektrike të cilat i
ekzekuton p.sh: një instruksion 1011000111001110.
Programet e ndërtuara në këtë gjuhë përbëhen vetëm nga kode binare (1
dhe 0), në kode të tilla jepen si instruksionet ashtu edhe adresat e qelizave
të memories. Programuesi duhet të njohë në detaje si punon kompjuteri,
prandaj quhet ndryshe gjuhë e nivelit të ulët.
Të mirat e gjuhës së makinës:
E vetmja e mirë është se programi i shkruar në gjuhë makine
ekzekutohet shumë shpejt nga kompjuteri pasi nuk ka nevojë për
ta përkthyer në gjuhën që kupton procesori dhe përdor në
mënyrë efikase Memorien Qëndrore.
Të metat e gjuhës së makinës:
Është e vështirë të programosh në gjuhë makine. Programisti
duhet të njohë detajet e harduerit për të shkruar një program.
Programisti duhet të mbajë mend shumë kode për të shkruar një
program, gjë që është burim gabimi .
Është e vështirë të korrigjohet (debug) një program i shkruar në
gjuhë makine.
Programim object-oriented Faqa 7
Gjuha assembler
Gjuha assembler ka qënë hapi i parë për të përmirësuar teknikën e
programimit. Meqënëse kompjuteri mund të njohë numrat dhe shkronjat
atëhere me anë të tyre u zëvëndësuan numrat në kodin e makinës.
Gjuha assembler është e ngjashme me gjuhën e makinës, me ndryshimin që
në gjuhën assembler përdoren mnemonika (shkurtime alfabetike) në vend të
kodimit binary, të cilat janë të lehta për t’u mbajtur mend. Psh, në vend të
një kombinimi njëshash dhe zerosh, për të paraqitur operacionin e
mbledhjes përdoret mnemonika ADD.
Po kështu përdoren adresa simbolike në vend të adresës absolute numerike.
Përpara se të përdoren nga kompjuteri, programet e shkruara në gjuhë
assembler duhet të përkthehen në gjuhë makine. Ky konvertim bëhet nga
një program përkthyes – gjuhësh i quajtur assembler.
Avantazhet e gjuhës asambler:
Është relativisht e lehtë të kuptohet dhe e kursen disi kohën e
programimit.
Është më e lehtë të korrigjohen gabimet dhe të modifikohen
instruksionet e programit.
Prodhimi i programeve efikase që zenë pak memorje dhe
ekzekutohen shumë më shpejt se programet në gjuhët e nivelit
të lartë.
Ka të njëjtën eficencë në ekzekutim si gjuha në nivel makine
mbasi ka një korespondencë një me një me urdhërat në gjuhë
makine.
Programim object-oriented Faqa 8
Të metat e gjuhës asambler:
E meta kryesore e saj është se varet nga tipi i kompjuterit
(procesori). Një program i shkruar në për një kompjuter mund të
mos ekzekutohet në një kompjuter me një procesor të një tipi
tjetër.
Gjuhët e nivelit të lartë
Përdorimi i gjuhës së nivelit të ulët kërkon një njohje të mirë të harduerit.
Ndërsa përdorimi i një gjuhe të nivelit të lartë kërkon vetëm të njihen
instruksione të shkruara në anglisht dhe llogjikën e problemit pavarësisht
nga tipi i kompjuterit që do të përdoret
Gjuhët e nivelit të lartë janë thjesht gjuhë që përdorin anglishten dhe
simbole matematike si +, -, /, (, =, etj për ndërtimin e një program.
Për shembull:
if (a>2) then a=3
ku if dhe then janë fjalë që prej gjuhës angleze përkthehen:
nëse (a>2) atëher a=3
Pra këtu, fjalën if procesori i kompjuterit automatikisht e "përkthen" ne BIT-a
(ang. binary digits). P.sh.: 101010101000.
Gjuhët e nivelit të lartë kanë nevojë të konvertohen në gjuhë makine për t’u
kuptuar nga kompjuteri. Para rreth 20 vjetësh gjuhët e nivelit të lartë ishin
gjuhë të orientuara ndaj problemit:
Programim object-oriented Faqa 9
Fortran (FORmula TRANslation) orientuar për probleme shkencore që
kanë shumë llogaritje
Cobol (COmmon Business Oriented Language) orientuar për probleme
ekonomike që kanë shumë të dhëna dhe pak llogaritje
Basic (Beginners All-purpose Symbolic Instruction Code) kryesisht për
fillestaret.
Gjuhët aktuale si Java, C++, Visual Basic janë gjuhë të nivelit të lartë gjithë-
qëllimshme që përdoren pavarsisht nga lloji i kompjuterit dhe i aplikimit, që
nga aplikime të izoluara deri në aplikime në internet.
Avantazhet e gjuhëve të nivelit të lartë:
Kuptohen lehtë
Përdoren lehtësisht
Është e lehtë të korigjohen gabimet dhe të modifikohen
instruksionet e programit
E meta e gjuhëve të nivelit të lartë:
Programi i shkruar në një gjuhë të nivelit të lartë duhet të
përkthehet në gjuhën e makines para se të ekzekutohet.
Programi i shkruar në një gjuhe të nivelit të lartë quhet program burim
(source program). Përkthimi nga gjuha e nivelit të lartë në gjuhë makine
bëhet nga një program i posaçëm. Programet e posaçme të përkthimit
ndahen në dy kategori:
Kompilatori (Compiler)
Interpretues (Interpreter)
Çdo gjuhë e nivelit të lartë ka përkthyesin e tij.
Programim object-oriented Faqa 10
Një kompilator përkthen një program të plotë, të quajtur kodi burim,
njëherësh në gjuhë makine. Sapo konvertohet programi, i quajtur kodi
object, ai është i regjistruar në formë të lexueshme nga makina. Kodi burim
mbetet i paprekur edhe pas konvertimit, si rrjedhojë mund të modifikohet
dhe të rikompilohet përsëri.
Një interpretues përkthen një program në gjuhë makine rresht për rresht
duke ekzekutuar cdo rresht të programit pasi ai është përkthyer. Në
shumicën e interpretuesve, forma e lexueshme nga makina nuk regjistrohet
në Memorjen Qëndrore apo në memorje ndihmëse, prandaj programi duhet
të interpretohet sa herë që ai ekzekutohet.
Përparësitë e Interpretuesit
Përgjigjet shpejt ndaj një ndryshimi në programin burim. Eleminohet
nevoja që të kontrollohet pjesa tjetër e programit.
Janë të lehtë në programim
Nuk kërkojnë shumë kujtesë
Të metat e Interpretuesit
Shpenzimi i madh i kohës mbasi çdo instruksion sa herë që duhet të
ekzekutohet duhet të përkthehet në kod makine
Programim object-oriented Faqa 11
2. Gjuha Visual Basic. Hyrje ne
gjuhen e programimit Visual Basic
dhe mjedisin e tij
Ne kete kapitull do te bejme nje paraqitje te shpejte te menyres se si
ndertohet nje aplikim ne Visual Basic. Do te njihemi me fjalorin e tij, me
strukturen e programit si dhe me mjedisin e punes ne Visual Basic. Ne kete
kapitull do te shkruajme programin e pare ne Visual Basic.
Objektivat e kursit
Avantazhet e perdorimit te Microsoft Visual Basic 6.0
Pervetesimi i koncepteve te programimit te orjentuar nga objektet,
terminologjise se re dhe mjevete te punes ne Visual Basic
Mesimi i elementeve themelore te ndertimit te nje aplikimi,
implementimit dhe shperndarjes se nje aplikimi ne Visual Basic
Perdorimi i mjeteve te punes (toolbox) te Visual Basic
Vetite e objekteve dhe menyrat e modifikimit te tyre
Metodat e objekteve
Dritarja e ndertimit te nderfaqes se aplikimit (design)
Testimi dhe korrigjimi i gabimeve me ndihmen e te ashtuquajturit
“debugging” dhe procedurat e trajtimit te gabimeve
Konceptet baze te trajtimit te bazave te te dhenave dhe menaxhimi
i tyre me ndihmen e kontrolleve te lidhur me databazen (databound
controls)
Programim object-oriented Faqa 12
Njohuri elementare mbi kontrollet ActiveX dhe Windows Application
Programming Interface (API)
Çfare eshte Visual Basic?
Visual Basic eshte nje mjet qe ju lejon te zhvilloni aplikime ne Windows
(Graphic User Interface - GUI). Aplikimet e krijuara kane nje paraqitje
familjare per perdoruesin.
Visual Basic eshte nje program i orientuar nga ngjarjet (event-driven), qe
do te thote se kodi ngelet i paekzekutuar derisa ai te thirret per ekzekutim si
pergjegje ndaj nje ngjarje te ndodhur (klikimit te nje butoni, zgjedhjes se nje
menuje, etj). Visual Basic qeveriset nga perpunues ngjarjesh. Asgje nuk
ndodh derisa te ndodhe nje ngjarje. Ne kete moment, kodi qe i
korrespondon asaj ngjarjeje ekzekutohet.
Event
Procedures
Programim object-oriented Faqa 13
Ngjarje? Perpunuesi i ngjarjeve
Kodi Kodi Kodi
Disa vecori te Visual Basic
Nje bashkesi e plote objektesh qe mund te perdoren ne aplikimin tuaj
Shume ikona dhe figura ne dispozicionin tuaj
Pergjigje ndaj veprimeve te mouse-it dhe tastjeres
Akses ne Clipboard dhe printer
Funskione te shumta grafike, matematikore dhe per perpunimin e
stringjeve
Trajtim te vektoreve me dimensione te fiksuara dhe dinamike. Mundesi
te krijimit te vektoreve te kontrolleve
Mbeshtet skedaret sekuenciale dhe ato te indeksua
Komoditet ne trajtimin e gabimeve
Mjete te fuqishme per trajtimin e bazave te te dhenave
Mundesi per krijimi e kontrilleve ActiveX
Krijimi i paketes instaluese lehteson shperndarjen e aplikimit tuaj
Visual Basic 6.0 kundrejt versioneve te meparshme te Visual Basic
Versionet origjinale te Visual Basic per DOS dhe Visual Basic per Windows
i kane fillimet e tyre ne vitin 1991.
Visual Basic 3.0 (nje hap shume i madh ne drejtim te permiresimit te
versioneve te meparshme) doli ne vitin 1993.
Visual Basic 4.0 doli ne vitin 1995 (versioni per mbeshtetjen e aplikimeve
32 bit).
Programim object-oriented Faqa 14
Visual Basic 5.0 doli ne vitin 1996. Mjedis i ri, mundesi per krijimin e
kontrolleve ActiveX, nuk suportohen me aplikmet 16 bit.
Disa nga risite e Visual Basic 6.0:
Kompilator me i shpejte
Kontrolli i ri ActiveX data Object (ADO)
Lejon intrgrimin e nje numri te larmishem bazash se te
dhenave
Ndertim i raporteve brenda aplikimit (Data report designer)
Krijimi i paketes instaluese (New Package & Deployment Wizard)
Rritje e mundesive te zhvillimit te aplikimeve per internet
16 Bits kundrejt 32 Bits
Aplikimet e zhvilluara ne Visual Basic 3.0 dhe ne versionin 16 bit te
Visual Basic 4.0 duhet te ekzekutohen ne Windows 3.1, Windows for
Workgroups, Windows NT, ose Windows 95
Aplikimet e zhvilluar ne versionin 32 bit te Visual Basic 4.0, Visual
Basic 5.0 dhe Visual Basic 6.0 mund te ekzekutohen ne versionet
Windows 95 e lart.
Ne kete kurs do te perdorim Visual Basic 6.0 ne Windows XP.
Programim object-oriented Faqa 15
Form 2 (.FRM) Form 3 (.FRM) Module 1 (.BAS)
Control 1
Control 3
Control 2
Control 4
Control 1
Control 3
Control 2
Control 4
Control 1
Control 3
Control 2
Control 4
Struktura e nje aplikimi ne Visual BasicProject (.VBP, .MAK)
Aplikimi (Project) perbehet nga:
Forms – Dritare qe mundesojne krijimin e nderfaqeve te aplikimit
Controls – Elemente grafike te shtuar ne forms-e per te mundesuar
bashkeveprimin e perdoruesit me aplikimin (text boxes, labels,
scroll bars, command buttons, etj.) (Forms dhe Controls jane
objekte.)
Properties – Cdo karakteristike e nje formsi ose kontrolli
specifikohet nga vetite. Psh disa nga vetite karakteristike te nje
kontrolli mund te jene names, captions, size, color, etj. Visual Basic
aplikon vetite default nese programisti nuk i ndryshon ato ne
momentin e ndertimit te aplikimit (design time) ose gjate
ekzekutimit te programit (run time).
Methods – Procedura te caktuara qe shkaktojne aktivizimin e
veprimeve te ndryshme te nje objekti te caktuar.
Programim object-oriented Faqa 16
Form 1 (.FRM)
Event Procedures – Pjese kodi e lidhur me nje objekt. Ky kod
ekzekutohet kur ndodh ngjarja perkatese.
General Procedures – Pjese kodi qe nuk ka lidhje me objektet.
Keto kode mund te thirren ne pjese te ndryshme te aplikimit.
Modules – Bashkesi procedurash, funksionesh, deklarim variablash,
konstantesh dhe tipe te reja te dhenash.
Programim object-oriented Faqa 17
Hapat e zhvillimit te nje Aplikimi
Tre jane hapat kryesore te ndertimit te nje aplikimi ne Visual Basic:
1. Vizatohet nderfaqja e perdoruesit
2. Vendosen vetite e kontrolleve
3. Shkruhet kodi
Le te shohim me hollesisht secilin hap.
Vizatimi i nderfaqes se perdoruesit dhe vendosja e vetive
Visual Basic operon ne tre menyra te ndryshme.
Menyra Design – perdoret per te ndertuar aplikimin
Menyra Run – perdoret per te ekzekutuar aplikimin
Menyra Break – ekzekutimi i aplikimit ndalon dhe aktivizohet
testuesi-rregulluesi i gabimeve (debugger)
Tani do te fokusohemi ne menyren design.
Gjashte dritare shfaqen ne momentin e hapjes se Visual Basic.
Dritarja Main konsiston ne shiritin e titullit (title bar), shiriti i
menuve (menu bar) dhe shiriti i butonave (toolbar). Shiriti i titullit
tregon emrin e projektit, menyren momentale te punes. Shiriti i
menuve permban te gjitha menute e Visual Basic environment.
Shiriti i butonave permban nje bashkesi butonash qe mundesojne
ekzekutimin e shpejte te disa prej komandave kryesore (te cilat
gjenden dhe ne bllokun e menuve). Ne dritaren kryesore
afishohen gjithashtu dhe kordinatat e formsit te zgjedhur ne
lidhje me pozicionin lart-majtas te ekranit (matur ne twips) si dhe
lartesia dhe gjeresia e tij.
Programim object-oriented Faqa 18
Dritarja Form eshte nje nga objektet me te rendesishme te
zhvillimit te nje aplikimi ne Visual Basic. Eshte ai objekt ne te
cilin ne “vizatojme” aplikimin tone.
Toolbox eshte objekti ku jane vendosur te gjithe kontrollet qe
perdoren ne aplikim.
Programim object-oriented Faqa 19
New form
Add project
Open project
Save project
Menu editor
Properties window
Code Editor Tasks
Form Layout
Run
Pause Stop
Project Explorer
Object Browser
Toolbox
Form position
Form dimensions
Dritarja Properties perdoret per te percaktuar vlerat fillestare
per te gjitha vetite e cdo objekti. Lista ne krye te dritares
permban te gjithe objektet e formsit te zgjedhur. Kjo dritare i
afishon vetite ne dy menyra te ndryshme: Alphabetic dhe
Categorized. Nen kete liste objektesh afishohen vetite e objektit
te zgjedhur.
Programim object-oriented Faqa 20
Pointer
Label
Frame
Check Box
Combo Box
Horizontal Scroll Bar
Timer
Directory List Box
Shapes
Image Box
Object Linking
Picture Box
Text Box
Command Button
Option Button
List Box
Vertical Scroll Bar
Drive List Box
File List Box
Lines
Data Tool
Dritarja Form Layout afishon ku (ne varesi te ekzekutimit
perkates) do te afishohet ne ekran formsi juaj gjate ekzekutimit
te programit:
Programim object-oriented Faqa 21
Dritarja Project afishon listen e te gjithe formseve dhe moduleve
qe perbejne aplikimin tuaj. Ne te mund te caktohet nese do te
shihet pamja e formsit (Form) apo dritarja e kodeve (Code).
Sic u permend me siper nderfaja per perdoruesin ‘vizatohet’ ne dritaren
form. Ka dy menyra per te vendosur nje kontroll ne nje forms:
1. Klikohet dy here ne kontrollin perkates ne dritaren toolbox dhe
kontrolli i zgjedhur vendoset ne qender te formsit me nje madhesi
te caktuar. Ju mund ta vendosni ne pozicionin e duhur dhe mund t’a
ridimensiononi sipas deshires.
2. Klikohet ne kontrollin perkates ne dritaren toolbox, e ne dritaren
form. Kursori ndryshon pamjen (kthehet ne nje kryq). Pozicionojeni
shigjeten e mouse-it ne pozicioni lart – majtas ku do te vendoset
kontrolli, shtypni butonin e majte te mouse-it dhe terhiqeni ate (pa
e leshuar) derisa te arrini ne pozicionin poshte – djathtas. Kur
leshohet butoni i majte i mouse-it kontrolli eshte vendosur ne
pozicionin dhe ne permasat e duhura.
Programim object-oriented Faqa 22
Per te zhvendosur nje kontroll te vendosur paraprakisht ne forms,
klikohet objekti dhe terhiqet (duke mbajtur butonin e majte te shtypur)
derisa te pozicionohet ne pozicionin e duhur.
Per te ridimensionuar nje kontroll, klikohet objekti ne forms,
pozicionohet shigjeta e mouse-it ne nje nga pikat e zgjedhjes qe jane
shfaqur ne skajet e objektit dhe duke u mbajtur i shtypur butoni i majte i
mouse-it terhiqet per te perftuar dimensionin e duhur.
Programim object-oriented Faqa 23
Klikoni ketu per te zhvendosur objektin
Perdorni pikat e zgjedhjes per te ridimensionuar objektin
Shembull 2-1
Kronometri – Shtimi i kontrolleve
1. Hapni nje projekt te ri. Qellimi i ketij projekti eshte te aktivizoje nje
timer, dhe ne momentin e stopimit te tij te llogarise kohen e kaluar
(ne sekonda).
2. Vendosni tre command buttons dhe gjashte labels ne form. Vendosini
kontrollet sic paraqitet ne dritaren e meposhteme:
Programim object-oriented Faqa 24
Percaktimi i vetive te objekteve ne momentin e dizenjimit (Design Time)
Cdo form dhe kontroll ka vlerat fillestare (default) per secilen vetit
(properties) ne momentin e hapjes se projektit. Ekzistojne dy rruge te
afishimit te dritares se vetive te nje objekti. Rruga e pare: klikohet ne
objektin e vendosur ne form dhe me pas ne dritaren Properties ose ne
butonin Properties Window te shiritit te butonave. Rruga e dyte : Klikohet
fillimisht ne dritaren Properties dhe me pas zgjidhet emri i objektit ne
listen Object te dritares Properties. Ne figuren e meposhteme paraqitet
dritarja Properties per aplikimin “Kronometri”:
Lista ne krye te dritares Properties eshte lista
Object. Ajo afishon emrat e te gjithe objekteve te vendosur ne form. Ne
figure paraqitet objekti Form. Lista e Vetive (Properties) paraqitet
menjehere ne vazhdim. Nje veti mund te zgjidhet duke klikuar ne te. Vlera e
Programim object-oriented Faqa 25
vetise mund te ndryshoje duke shtypur nje vlere te re ne vend te vleres se
vjeter ose duke zgjedhur nje vlere te re ne listen e vlerave te paracaktuara.
Vetite mund te afishohen ne rendin alfabetik (Alphabetic) (kete renditje e
prish vetem vetia Name qe per hir te rendesise se saj renditet e para) ose te
Kategorizuara (Categorized).
Nje veti shume e rendesishme per cdo objekt eshte vetia name. Kjo veti
perdoret nga Visual Basic per t’ju referuar nje objekti te caktuar ne kod.
Eshte mire qe per te emertuar objektet ne Visual Basic te perdoret nje
praktike e tille: emri i cdo objekti te kete si prefiks tre karaktere qe
karakterizojne llojin e objektit. Disa nga keto prefikse per tipet me
kryesore te objekteve jane:
Objekti Prefiksi Shembull
Form frm frmWatch
Command Button cmd, btn cmdExit, btnStart
Label lbl lblStart, lblEnd
Text Box txt txtTime, txtName
Menu mnu mnuExit, mnuSave
Check box chk chkChoice
Emrat e objekteve duhet te jene deri ne 40 karaktere te gjate, duhet te
fillojne me shkronje, duhet te permbajne vetem shkronja, numra, dhe
karakterin underscore (_). Emrat vendosen ne momentin e dizenjimit te
projektit ne dritaren Properties dhe perdoren ne kod sa here i referohet
atij objekti.
Programim object-oriented Faqa 26
Vendosja e vetive gjate ekzekutimit te programit (Run Time)
Vetite e nje objekti mund te vendosen ose ndryshohen dhe gjate
ekzekutimit te aplikimit. Per kete duhet te shkruhet kodi ne nje forme te
tille:
Emri_Objektit.Veti = Vlera_Re
Per shembull per te ndryshuar vetine BackColor te formsit me emer
frmStart, duhet te shkruajme kodin:
frmStart.BackColor = BLUE
Si perdoren emrat e objekteve ne ngjarjet e tyre (Object Events)
Emrat e objekteve perdoren nga Visual Basic per te percaktuar dhe te
gjithe bashkesine e procedurave te orjentuar nga ngjarjet (event-driven
procedures) tek te cilat ju mund te shtoni kodin tuaj. Formati per secilen
nga keto subrutina eshte:
Sub EmerObjekti_Ngjarje (Lista e argumentave (Opsionale))
.
.
End Sub
Ndermjet rreshtit Sub dhe End Sub ju mund te shtoni kodin tuaj.
Programim object-oriented Faqa 27
Shembull 2-2
Kronometri – Vendosja e vetive
1. Vendosni keto veti per formen, tre butonat dhe gjashte etiketat:
Form1:
BorderStyle 1-Fixed Single
Caption Kronometri
Name frmKronometri
Command1:
Caption Ora e &fillimit
Name cmdStart
Command2:
Caption Ora e &mbarimit
Name cmdEnd
Command3:
Caption &Dalje
Name cmdExit
Label1:
Caption Ora e fillimit
Label2:
Caption Ora e mbarimit
Label3:
Programim object-oriented Faqa 28
Caption Koha e kaluar
Label4:
BorderStyle 1-Fixed Single
Caption [bosh]
Name lblStart
Label5:
BorderStyle 1-Fixed Single
Caption [bosh]
Name lblEnd
Label6:
BorderStyle 1-Fixed Single
Caption [bosh]
Name lblElapsed
Ne vetine Caption te tre butonave vini re perdorimin e karakterit (& -
ampersand). Ai karakter mundeson stimulimin e ngjarjes click kur
shtypet tasta ALT e kombinuar me karakterin qe i paraprin karakterit
&. Pra ne rastin e mesiperm klikimi ne butonin ‘Ora e fillimit’ mund te
realizohet me ndihmen e kombinimit te tastave ALT+F. Shenojme se
ne paraqitjen e formes karakteri qe qe paraprihet nga karakteri &
shfaqet i nenvizuar (_).
Programim object-oriented Faqa 29
2. Forma do te kete kete pamje:
Programim object-oriented Faqa 30
Variablat
Se shpejti do te shtojme kodin e duhur ne aplikim. Me shtimin e objekteve
ne forms Visual Basic automatikisht nderton nje nje mjedis pune me te
gjitha procedurat e orjentura nga ngjarjet (event procedures). Ne nuk na
mbetet gje tjeter vecse te shtojme kodin e duhur ne ngjarjet qe duam te
aktivizojme. Por perpara se te bejme nje gje te tille le te flasim pak per
variablat.
Variablat perdoren nga Visual Basic per te mbajtur informacionin qe
nevojitet ne aplikim. Rregullat e perdorur per emertimin e variablave jane:
Jo me shume se 40 karaktere
Mund te permbajne shkronja, numra dhe (_)
Karakteri i pare duhet te jete shkronje
Nuk mund te perdrni nje fjale te rezervuar te Visual Basic
Tipet e te dhenave ne Visual Basic
Tipi Sufiksi
Boolean -
Integer %
Long (Integer) &
Single (Floating) !
Double (Floating) #
Currency @
Date -
Object -
String $
Variant -
Programim object-oriented Faqa 31
Deklarimi i Variablave
Ekzistojne tre menyra per deklarimin e variablave:
1. Default
2. Implicite
3. Eksplicite
Nqs nje variabel nuk deklarohet ne menyre implicite ose eksplicite
atehere automatikisht tipi i tij caktohet nga Visual Basic si variant. Tipi i
te dhenave variant eshte nje tip special te dhene qe perdoret nga Visual
Basic dhe nje variabel i tille mund te permbaje te dhena numerike, string
ose date.
Per te deklaruar ne menyre implicite nje variabel, perdorim sufiskin e
paraqitur ne tabelen e mesiperme (ne rastin kur ai ekziston). Per
shembull,
VlereTekst$ = "Ky eshte nje string"
Krijon nje variabel te tipit string, ndersa
Sasia% = 300
Krijon nje variabel integer.
Per te deklaruar nje variabel ne menyren eksplicite, fillimisht
percaktohet niveli i deklarimit te tij. Ekzistojne kater nivele deklarimi:
Niveli procedure
Niveli procedure, static
Niveli Form dhe module
Niveli Global
Programim object-oriented Faqa 32
o Bre nda nje procedura nje variabel deklarohet me ndihmen e
instruksionit Dim:
Dim VarInt as Integer
Dim VarDouble as Double
Dim Var1String, Var2String as String
Variablat ne nivel procedure te deklaruar ne kete menyre nuk e ruajne
vleren e tyre kur procedura perfundon se ekzekutuari.
o Per te mundesuar ruajtjen e vleres se nje variabli dhe kur procedura
perfundonse ekzekutuari, zevendesohet fjala celes Dim me fjalen
celes Static:
Static VarInt as Integer
Static VarDouble as Double
o Variablat ne nivel Formsi ose Moduli e juajne vleren e tyre dhe
mund te perdoren nga te gjitha procedurat e formsit ose modulit.
Keto variabla deklarohen ne seksionin declarations te objektit
general te dritares se kodit te formsit ose modulit. Per deklarimin e
tyre perdoret fjala celes Dim:
Dim VarInt as Integer
Dim VarDate as Date
o Variablat globale e ruajne vleren e tyre gjate gjithe kohes se
ekzekutimit te aplikimit dhe mund te perdoren nga te gjitha
procedurat e aplikimit. Keto variabla deklarohen ne seksionin
declarations te objektit general te dritares se kodit te nje moduli.
Keshillohet qe te gjithe variablat globale te deklarohen ne nje modul
te caktuar. Per deklarimin e tyre perdoret fjala celes Global:
Programim object-oriented Faqa 33
Global VarInt as Integer
Global VarDate as Date
Cfare ndodh nese deklarohen variabla me te njejtin emer ne dy apo me
shume vende? Variablat “me shume lokale” eklipsojne (kane precedence)
variablat “me pak lokale”. Psh. nqs nje variabel VarInt eshte deklaruar si
Global ne nje modul dhe eshte deklaruar si lokal ne proceduren Proc1, kur
ndodhemi ne proceduren Proc1, variabli qe mund te perdoret eshte variabli
lokal VarInt i procedures. Jashte procedures Proc1, variabli qe mund te
perdorim eshte variabli global VarInt.
Programim object-oriented Faqa 34
Shembull i niveleve te variablave:
Module1
Global X as Integer
Form1 Form2
Dim Y as Integer Dim Z as Single
Sub Rutine1() Sub Rutine3()
Dim A as Double Dim C as String
. .
. .
End Sub End Sub
Sub Rutine2()
Static B as Double
.
.
End Sub
Procedure Rutine1 ka te drejte te perdore variablat X, Y, dhe A (ato e
humbasin vleren kur procedura mbaron ekzekutimin)
Procedure Rutine2 ka te drejte te perdore variablat X, Y, dhe B (ato e
ruajne vleren)
Procedure Rutine3 ka te drejte te perdore variablat X, Z, dhe C (nuk i
ruajne vlerat)
Shembulli 2-3
Programim object-oriented Faqa 35
Kronometri – Shkrimi i kodit
Ajo qe mbetet te bejme eshte te shtojme ne aplikim kodin e duhur. Do te
shkruajme kod ne secilen ngjarje ku eshte e domosdoshme. Ne kete aplikim
jane tre ngjarje te tilla: klikoni ne secilin nga butonat.
1. Klikoni dy here ne form per te hapur dritaren e kodit. Ose zgjidhni ‘View
Code’ ne dritaren e projektit.
2. Klikoni shigjeten e listes ‘Object’ dhe zgjidhni objektin e quajtur general.
Ne listen e procedurave do te shfaqet declarations. Ketu do te deklaroni
tre variabla ne nivel formsi:
Option Explicit
Dim StartTime As Variant
Dim EndTime As Variant
Dim ElapsedTime As Variant
Instruksioni Option Explicit ben te detyrueshem deklarimin e te gjithe
variablave.
Tre rreshtat e tjere deklarojne perkatesisht variablat StartTime, EndTime,
dhe ElapsedTime si variabla globale te formsit.
3. Zgjidhni objektin cmdStart ne listen ‘Object’. Zgjidhni ne listen e
procedurave pikerisht proceduren Click nese ajo nuk eshte shfaqur
automatikisht. Shtypni ndermjet instruksioneve Sub dhe End Sub kodin e
meposhtem:
Programim object-oriented Faqa 36
Sub cmdStart_Click ()
‘Llogarit dhe afishon kohen e fillimit
StartTime = Now
lblStart.Caption = Format(StartTime, "hh:mm:ss")
lblEnd.Caption = ""
lblElapsed.Caption = ""
End Sub
Kjo procedure ben qe kur klikohet ne butonin Ora e fillimit, te lexohet koha
korrente dhe te afishohet ajo ne nje etikete. Ketu gjithashtu boshatisen
etiketat e tjera. Ne kodin e mesiperm dhe ne te gjithe kodet e tjera qe do te
shohim me pas, cdo rresht qe fillon me nje apostrof (‘) eshte nje koment. Ato
jane ne deshiren e programistit qe te perdoren dhe kane si qellim vetem
lehtesimin e leximit dhe sqarimit te programit dhe nuk merren parasysh nga
kompilatori.
4. Kodi ne butonin cmdEnd.
Sub cmdEnd_Click ()
‘Gjen oren korrente, llogarit kohen e kaluar
‘Vendos te dy vlerat ne etiketat perkatese
EndTime = Now
ElapsedTime = EndTime - StartTime
lblEnd.Caption = Format(EndTime, "hh:mm:ss")
lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss")
End Sub
Ketu, kur klikohet ne butonin Ora e mbarimit, lexohet ora korrente,
llogaritet koha e kaluar dhe i vendos te dy vlerat ne etiketat perkatese.
Programim object-oriented Faqa 37
5. Kodi ne butonin cmdExit.
Sub cmdExit_Click ()
End
End Sub
Ketu i jepet fund aplikimit me ndihmen e instruksionit End ne momentin e
klikimit ne butonin Exit.
6. Vini re qe Visual Basic ne momentin e shkrimit te kodit ben automatikisht
dhe kontrollin sintaksor te kodit te shkruar.
7. Ekzekutoni aplikimin duke shtypur butonin Run ne shiritin e butonave ose
duke shtypur tasten <f5>.
8. Ruani aplikimin - shihni sqarimin ne faqen pasardhese. Perdorini
komanden Save Project As nen menune File. Sigurohuni per regjistrimin
edhe te formes dhe te projektit.
9. Shtoni disa elemente te tjera ne aplikimin e mesiperm:
A. Ndryshoni ngjyren e formes dhe tipin e shkrimit te perdorur ne
etiketat dhe butonat e perdorur.
B. Kini parasysh se butoni ‘Ora e mbarimit’ mund te shtypet para
butonit ‘Ora e fillimit’. Nje gje e tille nuk duhet te ndodhe.
Ndryshojeni aplikimin ne menyre qe te mos lejohet nje gje e tille.
(Perdorni vetine Enabled te butonit).
C. Si mund te afishoni ne menyre te vazhdueshme vlerat perkatese
ne etiketat ‘Ora e mbarimit’ dhe ‘Koha e kaluar’? Kjo eshte pak e
nderlikuar fale natyres se Visual Basic si nje gjuhe e orjentuar
nga ngjarjet. Shihni objektin timer.
Programim object-oriented Faqa 38
Ruajtja e nje aplikimi ne Visual Basic:
Gjate ruajtjes se nje aplikimi ne Visual Basic, ju duhet te beni kujdes te ruani
te gjithe elementet e tij: formset (.FRM), modulet (.BAS) dhe skedarin e
projektit (.VBP). Gjithashtu duhet patur kujdes qe ruajtja e tyre te behet ne
direktorite e duhura. Ne dritaren Save shfaqet fillimisht direktoria korrente.
Perdorni teknikat standarde te windows-it per t’u pozicionuar ne direktorine e
deshiruar.
Ekzistojne kater komanda Save ne menune File te Visual Basic:
Save [Form Name] Regjistron formsin ose modulin e zgjedhur me emrin
aktual. Skedari i zgjedhur identifikohet ne dritaren
Project.
Save [Form Name] As Njesoj si Save, si dhe mundeson regjistrimin e
objektit te zgjedhur me nje emer tjeter.
Save Project Regjistron te gjithe formset dhe modulet ne projektin
aktual duke perdorur emrat e tyre. Regjistron
gjithashtu dhe skedarin e projektit.
Save Project As Njesoj si Save Project, por mundeson dhe ndryshimin
e emrave te skedareve.
Programim object-oriented Faqa 39
Ushtrimi 2
Kalendari/Afishimi i ores
Ndertoni nje dritare qe afishon daten korrente (daten, dite, muajin dhe vitin)
Afishoni gjithashtu oren korrente, qe rifreskohet cdo sekond (per kete
perdorni kontrollin Timer). Perdorni vetite e objekteve per nje paraqitje sa
me te kendeshme.
Zgjidhja:
Form:
Vetite:
Form frmCalendar:
Caption = Kalendari
BorderStyle = 1 - Fixed Single
Timer timDisplay:
Interval = 1000
Label lblDay:
Programim object-oriented Faqa 40
lblDay
lblTime
timDisplay
lblMonth
lblNumber
lblYear
Caption = Sunday
FontName = Times New Roman
FontBold = True
FontSize = 24
Label lblTime:
Caption = 00:00:00 PM
FontName = Times New Roman
FontBold = True
FontSize = 24
Label lblYear:
Alignment = 2 - Center
Caption = 1998
FontName = Times New Roman
FontBold = True
FontSize = 24
Label lblNumber:
Alignment = 2 - Center
Caption = 31
FontName = Arial
FontBold = True
FontSize = 72
Programim object-oriented Faqa 41
Label lblMonth:
Alignment = 2 - Center
Caption = March
FontName = Times New Roman
FontBold = True
FontSize = 24
Kodi:
General Declarations:
Option Explicit
Ngjarja Timer e kontrollit timDisplay:
Private Sub timDisplay_Timer()
Dim Today As Variant
Today = Now
lblDay.Caption = Format(Today, "dddd")
lblMonth.Caption = Format(Today, "mmmm")
lblYear.Caption = Format(Today, "yyyy")
lblnumber.Caption = Format(Today, "d")
lblTime.Caption = Format(Today, "h:mm:ss ampm")
End Sub
Programim object-oriented Faqa 42
3. Gjuha Visual Basic.
Instruksione dhe shprehjet në
Visual Basic
Përsëritje
Në kapitullin e fundit u trajtuan tre hapat kryesorë për zhvillimin e një
aplikimi në Visual Basic:
1. Vizatimi i ndërfaqes së përdoruesit
2. Përcaktimi i vetive të kontrolleve
3. Shkrimi i kodit
Në këtë kapitull do të vazhdojmë të përqëndrohemi në hapin e tretë,
shkrimin e kodit. Do të familjarizoheni më shumë me dritaren e shkrimit të
kodit, dhe do të mësoni disa elemente të tjera të gjuhës Visual Basic.
Programim object-oriented Faqa 43
Një histori e shkurtër e Basic
Gjuha Basic është zhvilluar në kolegjin e Dartmouth ne vitin 1960:
B (eginner's)
A (All-Purpose)
S (Symbolic)
I (Instruction)
C (Code)
Si përgjigje ndaj gjuhëve më të komplikuara të programimit FORTRAN,
Algol, Cobol, etj.
Në mes të viteve 1970, dy studentë kolegji shkruajtën versionin e parë të
Basic-ut për një mikrokompjuter. Besoj se keni dëgjuar për ato studentë,
për Bill Gates dhe Paul Allen!
Cdo version i mëvonshëm i Basic-ut mbështetet në mënyrë esenciale në
atë version të hershëm. Të tillë ishin versionet GW-Basic, QBasic,
QuickBasic.
Versioni i parë i Visual Basic i ka fillimet në vitin 1991.
Programim object-oriented Faqa 44
Instruksione dhe shprehjet në Visual Basic
Instruksioni mëi thjeshtë është ai i vlerëdhënies. Ai përbëhet nga emri i
variablit, i ndjekur nga operatori i vlerëdhënies (=) dhe më pas nga një
shprehje.
Shembuj:
StartTime = Now
Explorer.Caption = "Përshëndetje"
NrBit = NrByte * 8
Shpejtësia = Rrugë * Kohë
a = b - c
Instruksionet e vlerëdhënies shërbejnë për të ruajtur një informacion në
një variabël.
Në përgjithësi instruksionet shkruhen nga një në çdo rresht. Por ekziston
edhe mundesia e shkruajtjes së disa instruksioneve në një rresht duke
përdorur dy pikat (:) per t’i ndarë ato:
StartTime = Now : EndTime = StartTime + 10
(Duhet patur kujdes në shkrimin e disa instruksioneve në një rresht
sidomos në rastin e strukturave If/End If.)
Nqs një instruksion është shume i gjatë ai mund të vazhdojë në rreshtin
tjetër duke përdorur karakterin e vazhdimit (_). Shembull:
Muaji = Log(Finale * IntVlera / Depozita + 1) _
/ Log(1 + IntVlera)
Komentet fillojnë me fjalën çelës Rem ose me një apostrof ('). Shembull:
Rem Ky është një koment
' Ky është gjithashtu një koment
Programim object-oriented Faqa 45
x = 2 * y 'një tjetër koment
Eshtë programisti ai që vendos se ku do të përdoren komentet në
program. Komentet mundësojnë sqarimin e programit dhe e bëjnë atë më
të kuptueshëm dhe të lexueshëm.
Operatorët e Visual Basic
Operatorët më të thjeshtë janë operatorët aritmetikë. Lista e tyre e
renditur sipas përparësisë së tyre është:
Operatori Veprimi
^ Fuqia
* / Shumëzimi dhe pjestimi
\ Pjestimi i plotë
Mod Mbetja
+ - Mbledhja dhe zbritja
Kllapat në një shprehje shërbejnë për të ndryshuar përparësitë e
operatorëve.
Për bashkimin e dy stringjeve përdoren operatorët & ose + :
lblTime.Caption = "Ora korrente është " & Format(Now, “hh:mm”)
txtShembull.Text = "Pershendetje “ + “miq”
Operatorët e krahasimit në Visual Basic janë gjashtë:
Programim object-oriented Faqa 46
Operatori Krahasimi
> Më i madh se
< Më i vogël se
>= Më i madh i barabartë se
<= Më i vogël i barabartë se
= I barabartë me
<> I ndryshëm nga
Rezultati i krahasim është një shprehje me vlerë Boolean-e të vërtetë ose
të gabuar (True ose False).
Tre operatorët logjik
Operatori Veprimi
Not Jo
And Edhe logjike
Or Ose logjike
Operatori Not ndryshon në të kundërt vlerën e një shprehjeje.
Operatori And kthen vlerën True nqs të dy operandët janë me vlerë
True dhe vlerën False në të kundërt.
Operatori Or kthen vlerën True nqs të paktën njëri nga operandët
është True dhe vlerën False në të kundërt.
Përsa i takon përparësisë operatoret logjik vijnë pas operatorëve
aritmetik.
Programim object-oriented Faqa 47
Programim object-oriented Faqa 48
Funksionet e Visual Basic
Visual Basic ofron nje gamë të gjerë funksionesh të gatshme. Help-i i
Visual Basic jep nje informacion të pasur dhe të hollësishëm për mëyrë e
përdorimit të secilit prej tyre. Disa shembuj funksionesh jane:
Funksioni Vlera e kthyer
Abs Vlera absolute e numrit
Asc Kodi ASCII i një karakteri
Chr Karakteri që i korrespondon kodit ASCII të dhënë
Cos Kosinusi i një kendi
Date Data e momentit e konvertuar në string
Left Karakteret në të majtë të një stringu
Len Numri i karaktereve të një stringu
Now Data dhe ora e momentit
Right Karakteret në të djathtë të një stringu
Rnd Një numer i rastit (nga 0 ne 1)
Sin Sinusi i një kendi
Sqr Rrënja katrore e një numri
Str Një numer i konvertuar në string
Time Ora e momentit e konvertuar në string
Timer Numri i sekondave të kaluar nga mesnata
Val Vlera numerike e një stringu të dhënë
Programim object-oriented Faqa 49
Funksioni Rnd
Gjatë shkrimit të tipeve të ndryshme të programeve por sidomos në ato
të lojrave lind nevoja e gjenerimit të numrave të rastit. Në Visual Basic një
gjë e tillë realizohet me ndihmën e funksionit Rnd. Sa herë ekzekutohet
programi ky funksion gjeneron numra të ndryshem nga 0 ne 1. Për të
gjeneruar numra të plotë të rastit Në intervalin NrMin dhe NrMax,
përdoret formula:
Nr = Int((NrMax - NrMin + 1) * Rnd) + NrMin
Në mënyrë që vargu i numrave të rastit të jetë i ndryshëm në çdo
ekzekutim të programit përdoret instruksioni Randomize
Ky instruksion mund të vendoset në Form_Load ose në secilën nga
procedurat
që përdoret për gjenerimin e numrave të rastit.
Shembull:
Numrat e rastit të gjeneruar si rezultat i hedhjes së një zari:
Nr = Int(6 * Rnd) + 1
Për të zgjedhur një numë të rastit ndërmjet 100 dhe 200, përdorim:
Numer = Int(101 * Rnd) + 100
Programim object-oriented Faqa 50
Shembull 23
Depozitat e kursimit
1. Hapni një projekt të ri. Qëllimi i këtij projekti është të përcaktojë sa
është fitimi juaj nëse vendosni të depozitoni një sasi parash në një
bankë. Formula matematikore që llogarit interesin është:
F = D [ (1 + I)M - 1] / I
ku
F – Sasia përfundimtare e parave
D – Depozita mujore
I – Interesi vjetor
M – Numri i muajve
2. Vendosni në forms 4 label, 4 text box-e, dhe 2 butona. Formsi duhet të
ketë një paraqitje të tille:
Programim object-oriented Faqa 51
3. Vendosni keto veti per formen dhe kontrollet e tjera:
Form1:
BorderStyle 1-Fixed Single
Caption Depozita kursimit
Name frmSavings
Label1:
Caption Depozita mujore
Label2:
Caption Intersi vjetor
Label3:
Caption Numri i muajve
Label4:
1 Caption Balanca përfundimtare
Text1:
Text [bosh]
Name txtDeposit
Text2:
Text [bosh]
Name txtInterest
Text3:
Text [bosh]
Programim object-oriented Faqa 52
Name txtMonths
Text4:
Text [bosh]
Name txtFinal
Command1:
Caption &Llogarit
Name cmdCalculate
Command2:
Caption &Dalje
Name cmdExit
Tashmë forma do të ketë një pamje të tillë:
4. Deklaroni katër variabla në seksionin general declarations të formës.
Deklarimi në këtë seksion i bën këto variabla të përdorshëm nga të gjitha
procedurat e formës:
Option Explicit
Programim object-oriented Faqa 53
Dim Deposit As Single
Dim Interest As Single
Dim Months As Single
Dim Final As Single
Theksojmë se instruksioni Option Explicit shërben për të bërë të
detyrueshëm deklarimin e variablave.
5. Shkruani kodin e mëposhtëm në ngjarjen Click të butonit cmdCalculate.
Private Sub cmdCalculate_Click ()
Dim IntRate As Single
‘lexon vlerat nga text box-et
Deposit = Val(txtDeposit.Text)
Interest = Val(txtInterest.Text)
IntRate = Interest / 1200
Months = Val(txtMonths.Text)
‘Llogarit vlerën dhe e vendos në text box-in përkatës
Final = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
txtFinal.Text = Format(Final, "#####0.00")
End Sub
Ky kod lexon tre vlerat hyrëse (depozita mujore, interesi vjetor, numri i
muajve) nga text box-et perkatëse, llogarit balancën përfundimtare duke
përdorur formulën e përcaktuar më sipër, dhe afishon rezultatin në një
tjetër text box.
6. Shkruani kodin e mëposhtëm në ngjarjen Click të butonit cmdExit.
Private Sub cmdExit_Click ()
End
Programim object-oriented Faqa 54
End Sub
7. Ekzekutojeni programin dhe testoni saktësinë e tij me disa shembuj. Kur
të siguroheni që ai funksionon saktësisht regjistrojeni.
Programim object-oriented Faqa 55
Konstantet simbolike të Visual Basic
Shpesh herë në Visual Basic, funksionet dhe objektet kërkojnë argumenta që
ndikojnë në veprimin e tyre dhe në vlerat që ato kthejnë. Këto argumenta
janë konstante numerike, vlera e të cilave nuk ndihmon në interpretimin e
tyre. Për t’i bërë këto konstante më të kuptueshme, Visual Basic i vendos
vlerave më të përdorura një emër duke krijuar kështu të ashtuquajturat
konstante simbolike. Apendix-i paraqet listën e shumë prej këtyre
konstaneve.
Për shmbull, për të ngjyrosur me blu sfondin e një forme të quajtur
frmShembull, mund të shkruani:
frmShembull.BackColor = 0xFF0000
ose, mund të përdoret konstantja simbolike e ngjyres blu (vbBlue):
frmShembull.BackColor = vbBlue
Rekomandohet që të përdoren konstantet simbolike sa herë që një gjë e tillë
është e mundur në vend të vlerave numerike. P.sh. vbBlue është shumë më
domethënëse se sa vlera 0xFF0000 pavarësisht se të dyja përfaqsojnë të
njëjtën vlerë. Për më tepër këto konstante simbolike nuk është nevoja që të
deklarohen pasi ato vijnë bashkë me Visual Basic.
Programim object-oriented Faqa 56
Deklarimi i konstanteve nga përdoruesi
Ju gjithashtu mund të deklaroni konstantet tuaja të cilat mund të përdoren
më pas gjithkund në program. Formati i deklarimit të konstantes PI me
vlerë 3.14159 është:
Const PI = 3.14159
Konstante e deklaruara nga përdoruesi është mirë që të shkruhem
me shkronja të mëdha për t’i dalluar ato nga variablat. Jetëgjatësia dhe
zona e përcaktimit të një konstanteje ndjek të njëjtat rregulla si dhe për
variablat. Pra e deklaruar në një procedurë ajo është lokale në atë
procedure, e deklaruar në seksionin general declarations të formës, ajo
është globale për atë form. Për të krijuar një konstate globale për të gjithë
aplikimin, përdorim formatin:
Global Const PI = 3.14159
në seksionin general declarations të një moduli.
Programim object-oriented Faqa 57
Instruksionet e degëzuara në Visual Basic – instruksioni If
Instruksionet e degëzuara përdoren për të ekzekutuar një bashkësi
instruksionesh në rast se plotësohet një kusht i caktuar.
Instruksioni i tillë më i thjeshtë është If/Then:
If Balance - Terheq < 0 Then Print "Ju nuk mund të tërhiqni
këtë sasi parash"
Këtu, n.q.s. dhe vetëm n.q.s. Balance - Terheq është më e vogël se zero,
afishohet në ekran mesazhi: "Ju nuk mund të tërhiqni këtë sasi parash".
Në këtë rast është e detyrueshme që instruksioni të shkruhet në një
rresht të vetëm.
Në rast se kur është i vërtetë kushti duhet të ekzekutohen më shumë se
një instruksione atëherë përdoret instruksioni If/Then/End If:
If Balance - Terheq < 0 Then
Print "Ju nuk mund të tërhiqni këtë sasi parash"
Print "Kërkohet autorizim"
End If
Në këtë rast kur Balance – Terheq është më e vogël se zero, ne ekran
afishohen dy rreshta informacion.
Instruksioni If/Then/Else/End If:
If Balance - Terheq < 0 Then
Print "Ju nuk mund të tërhiqni këtë sasi parash"
Print "Kërkohet autorizim"
Else
Programim object-oriented Faqa 58
Balance = Balance - Terheq
End If
Në këtë rast kur (Balance - Terheq < 0), afishohen dy rreshtat si në
shembullin e mësipërm, por në rast se ai kusht nuk është i vërtete (Else)
ekzekutohet instruksioni që llogarit vlerën e re të Balances pas tërheqjes
së parave.
Instruksionit If/Then/Else/End If përpara Else, mund t’i shtohen dhe
instruksione të tjera ElseIf:
If Balance - Terheq < 0 Then
Print "Ju nuk mund të tërhiqni këtë sasi parash"
Print "Kërkohet autorizim"
ElseIf Balance - Terheq = 0 Then
Print "I tërhoqët të gjitha paratë që dispononit"
Balance = 0
Else
Balance = Balance - Terheq
End If
Tani është shtuar një kusht i ri. N.q.s. Balance është e barabartë me Terheq
(ElseIf Balance - Terheq = 0), afishohet një mesazh tjeter dhe barazohet me
0 vlera e Balance.
Gjatë përdorimit të instruksioneve të degëzuara kini kujdes të konsideroni të
gjitha rastet e mundëshme në strukturën If/Else/End If. Gjithashtu duhet të
dini që çdo kusht If dhe ElseIf testohet në mënyrë të njëpasnjëshme. Në
momentin që një kusht plotësohet instruksionet e lidhur me të ekzekutohen
dhe menjëherë bëhet dalja nga struktura If/Then/ElseIf/Else/End If
pavarësisht se mund të ketë dhe kushte të tjera që plotësohen në ElseIf në
vazhdim. Instruksione e lidhura me këto kushte nuk do të ekzekutohen kurrë.
Programim object-oriented Faqa 59
Kontrolli i Tastave të shtypura
Nëse keni parasysh shembullin e mëparshëm përdoruesi gjatë ekzekutimit të
programit mund të shtypë çfarëdo karaktersh (dhe shkronja) në fushat që
parimisht duhet të përmbajnë vetëm numra. Në një rast të tillë është detyrë
e programistit që të kufizojë lirinë e përdoruesit dhe të lejojë shtypjen vetëm
të tastave të lejuara. Një procedurë e tillë quhet “Kontrolli i tastave të
shtypura”
Ky kontroll realizohet nëpërmjet ngjarjes KeyPress të një objekti. Kjo
procedure ka një formë të tillë (për text box e quajtur txtText):
Sub txtText_KeyPress (KeyAscii as Integer)
.
.
.
End Sub
Instruksionet e kësaj procedure ekzekutohen sa herë që shtypet një tastë në
text box-in përkatës, kodi ASCII i tastës së shtypur kalohet si argument i
procedurës në variablin KeyAscii. N.q.s. KeyAscii është një vlerë e lejuar, nuk
bëhet asgje, në të kundërt, kur vlera e KeyAscii nuk është një vlerë e lejuar
ajo barazohet me zero dhe dilet nga procedura. Një gjë e tillë ka të njëjtin
rezultat si të mos ishte shtypur asnjë tastë. Tabela e kodeve ASCII paraqitet
në fund të këtij kapitulli. Atë mund ta gjeni gjithashtu dhe në help-in e Visual
Basic. Gjithashtu disa tasta krahas vlerave përkatëse në tabelën e kodeve
ASCII paraqiten dhe me konstantet simbolike.
Supozojmë se keni një text box (me emër txtShembull) dhe doni të lejoni
shkrimin në të vetëm të shkronjave të mëdha (kodet ASCII të të cilave i
takojnë segmentit 65 - 90, ose po të përdoren konstantet simbolike nga
Programim object-oriented Faqa 60
vbKeyA deri vbKeyZ). Procedura KeyPress e text box-it përkatës do të
ishte e tillë (Beep shkakton një tingull në rast se një tastë e palejuar
shtypet):
Sub txtShembull_KeyPress(KeyAscii as Integer)
If KeyAscii >= vbKeyA And KeyAscii <= vbKeyZ Then
Exit Sub
Else
KeyAscii = 0
Beep
End If
End Sub
Gjatë kontrollit të tastave të shtypura, është e këshillueshme të lejohet në
çdo rast shtypja e tastës backspace (me kod ASCII 8; konstante simbolike
vbKeyBack). Në të kundërt në atë text box nuk do të ishte i mundur
korrigjimi.
Programim object-oriented Faqa 61
Shembull 3-2
Depozita e kursimit – Kontrolli i tastave të shtypura
1. Vlerat e lejuara të kodeve ASCII në fushat ku përdoruesi duhet të shtypë
të dhënat e tij janë nga 48 deri në 57 (numrat), 46 (presja dhjetore), dhe
8 (tasta backspace). Në kodin e mëposhtëm do të përdoren konstantet
simbolike për numrat dhe tastën backspace. Një konstante e tillë nuk
ekziston për presjen dhjetore, kështu që mund të krijohet një e tillë nga
instruksioni i mëposhtëm në seksionin general declarations:
Const vbKeyDecPt = 46
2. Shtoni kodin e mëposhtëm në tre procedurat: txtDeposit_KeyPress,
txtInterest_KeyPress, dhe txtMonths_KeyPress.
Private Sub txtDeposit_KeyPress (KeyAscii As Integer)
‘Lejon vetëm numrat, presjen dhjetore dhe tastën backspace
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyDecPt Or KeyAscii = vbKeyBack Then
Exit Sub
Else
KeyAscii = 0
Beep
End If
End Sub
Private Sub txtInterest_KeyPress (KeyAscii As Integer)
‘Lejon vetëm numrat, presjen dhjetore dhe tastën backspace
Programim object-oriented Faqa 62
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyDecPt Or KeyAscii = vbKeyBack Then
Exit Sub
Else
KeyAscii = 0
Beep
End If
End Sub
Private Sub txtMonths_KeyPress (KeyAscii As Integer)
‘Lejon vetëm numrat, presjen dhjetore dhe tastën backspace
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyDecPt Or KeyAscii = vbKeyBack Then
Exit Sub
Else
KeyAscii = 0
Beep
End If
End Sub
(Në instruksionet e mësipërme If, Wordi shkakton një kalim në rresht të ri
duke e paraqitur instruksionin If në dy rreshta, ndërkohë që në Visual
Basic ai duhet të jetë një rresht i vetëm. Një shënim i tillë do të vlejë për
të gjitha rastet e njëjta në vazhdim të këtij kursi.)
3. Riekzekutoni programin dhe testoni saktësinë e tij.
Programim object-oriented Faqa 63
Select Case – Një tjetër instruksion i degëzuar
Përveç instruksionit If/Then/Else, edhe formati Select Case mund të
përdoret kur ekzistojnë shumë zgjedhje të mundëshme.
Shembull i përdorimit të instruksionit If:
If Mosha = 5 Then
Kategoria = "Femijë 5 vjeçar”
ElseIf Mosha >= 13 and Mosha <= 19 Then
Kategoria = "Adoleshent"
ElseIf (Mosha >= 20 and Mosha <= 70) Then
Kategoria = "I rritur"
ElseIf Mosha > 70 Then
Kategoria = "Moshë e thyer"
Else
Kategoria=”Te tjerët”
End If
Kodi korrespondues me Select Case do të ishte:
Select Case Mosha
Case 5
Kategoria = " Femijë 5 vjeçar "
Case 13 To 19
Kategoria = "Adoleshent"
Case 20 To 70
Programim object-oriented Faqa 64
Kategoria = "I rritur"
Case Is > 70
Kategoria = " Moshe e thyer "
Case Else
Kategoria = "Te tjerët"
End Select
Vini re përdorimin e disa formateve të përdorimit të instruksionit Case.
Programim object-oriented Faqa 65
Instruksioni GoTo
Një tjetër instruksioni i degëzimit dhe ndoshta instruksioni më i padëshiruar
në programim është instruksioni GoTo. Ai ka një përdorim të gjerë në rastet
e trajtimit të gabimeve. Formati i tij është GoTo Etiketë, ku Etiketë është
“emërtimi i një rresht. Emërtmi i rreshtit realizohet duke shtypur Etiketën të
pasuar nga dy pikat (:).
Shembull i përdorimit të instruksionit GoTo:
Rreshti10:
.
.
GoTo Rreshti10
Kur ekzekutimi i kodit mbërrin në instruksionin GoTo, kontrolli i programit
transferohet në rreshtin e etiketuar Rreshti10.
Programim object-oriented Faqa 66
Ciklet në Visual Basic
Një nga formatet e përdour nga Visual Basic për të realizuar instruksionet
ciklikë është formati Do/Loop. Ciket përdoren për të mundësuar
ekzekutimin e disa instruksioneve në mënyrë të përsëritur, një numër të
caktuar herësh. Kjo përsëritje realizohet derisa plotësohet një kusht i
caktuar i vendosur në fillim ose në fund të ciklit.
Cikli Do While/Loop:
Nr = 1
Do While Nr <= 1000
Debug.Print Nr
Nr = Nr + 1
Loop
Ky cikël përsëritet për sa kohë që (While) variabli Nr është më i vogël ose
i barabartë me 1000. Duhet patur parasysh se struktura ciklike Do
While/Loop mund të mos ekzekutohet asnjë herë nëse kushti pas While
nuk është i vërtetë që në momentin e parë. Vini re dhe përdorimin e
instruksionit Debug.Print. Ky instruksion mundëson afishimin e vlerës së
Variablit Counter në dritaren Debug të Visual Basic (kjo dritare mund të
hapet me Ctrl+G). Më hollësisht me këtë dritare do të njiheni në leksionet
e mëvonshme.
Ekuivalent i ciklit Do While/Loop është dhe cikli While/Wend
Programim object-oriented Faqa 67
Cikli Do Until/Loop:
Nr = 1
Do Until Nr > 1000
Debug.Print Nr
Nr = Nr + 1
Loop
Instruksionet e këtij cikli ekzekutohet derisa (Until) variabli Nr të kalojë
vlerën 1000. Struktura Do Until/Loop mund të mos ekzekutohet asnjë
herë, nëse kushti pas Until është i vërtetë që në momentin e parë.
Cikli Do/Loop While:
Shuma = 1
Do
Debug.Print Shuma
Shuma = Shuma + 3
Loop While Shuma <= 50
Ky cikël ekzekuton në mënyrë të përsëritur instruksionet përkatëse për sa
kohë që (While) vlera e variablit Shuma është më e vogël ose e barabartë
me 50. Meqë kontrolli i kushtit në këtë rast bëhet në fund të strukturës
ciklike Do/Loop While, isntruksionet e ciklit ekzekutohen të paktën një
herë.
Do/Loop Until Example:
Shuma = 1
Do
Debug.Print Shuma
Shuma = Shuma + 3
Programim object-oriented Faqa 68
Loop Until Shuma > 50
Ky cikël përsëritet derisa (Until) vlera e variablit Shuma të bëhet më e
madhe se 50. Për të njëjtat arsye si në shembullin e mësipërm struktura
Do/Loop Until ekzekutohet të paktën një herë.
Kini kujdes të ndërtoni kushte të tilla që të sigurojnë daljen nga cikli! Ciklet e
pafundme nuk janë asnjëherë të këndëshme. Nëse hyni në një të tillë
provoni të dilni duke pëerdorur kombinimin Ctrl+Break. Në rastet kur një
gjë e tillë nuk funksionon rruga e vetme është fikja e kompjuterit!
Instruksioni Exit Do ju nxjerr jashtë ciklit dhe transferon kontrollin e
programit në instruksionin që ndjek ciklin Loop.
Cikli For/Next
For I = 1 to 50 Step 2
A = I * 2
Debug.Print A
Next I
Në këtë shembull, variabli i ciklit I inicializohet me 1 dhe pas çdo hapi të
ekzekutimit të instruksioneve të strukturës ciklike For/Next, rritet me 2
(Step). Në mungesë të fjalës çelës Step variabli i ciklit rritet me 1 (lejohen
dhe vlera negative të hapit). Përsëritja e instruksioneve të ciklit vazhdon
derisa variabli I bëhet më i madh ose i barabartë me vlerën përfundimtare
(50).
Ndryshe nga strukturat ciklike Do/Loop struktura For/Next përdoret vetëm
në rastet kur dihet paraprakisht numri i herëve që do të ekzekutohen
instruksionet e ciklit.
Programim object-oriented Faqa 69
Për të dalë nga cikli For/Next përdoret instruksioni Exit For. Ai transferon
kontrollin e programit në instruksionin që ndjek instruksionin Next.
Programim object-oriented Faqa 70
Shembull 3-3
Savings Account - Decisions
1. Në këtë shembull, do të modifikojmë projectin Savings Account duke
lejuar te shruhen 3 vlera dhe të llogaritet automatikisht vlera e katërt.
Sillimish shtoni butonin e tretë I cili do të boshatisë gjithë text boxes.
Përcaktoni vetitë e tij si më poshtë:
Command3:
Caption Clear &Boxes
Name cmdClear
Pasi të keni mbaruar, Forma do të duket:
2. Shkruani kodin më poshtë në ngjarjen Click të cmdClear:
Private Sub cmdClear_Click ()
‘Blank out the text boxes
txtDeposit.Text = ""
Programim object-oriented Faqa 71
txtInterest.Text = ""
txtMonths.Text = ""
txtFinal.Text = ""
End Sub
Me klikim të butonit Clear ky kod boshatis përmbajtjen e 4 text boxeve.
3. Shrkuani kodin më poshtë në ngjarjen KeyPress të objektit txtFinal:
Private Sub txtFinal_KeyPress (KeyAscii As Integer)
‘Only allow number keys, decimal point, or backspace
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyDecPt Or KeyAscii = vbKeyBack Then
Exit Sub
Else
KeyAscii = 0
Beep
End If
End Sub
4. Modifikoni kodin në ngjarjen Click të butonit cmdCalculate:
Private Sub cmdCalculate_Click()
Dim IntRate As Single
Dim IntNew As Single
Dim Fcn As Single, FcnD As Single
‘Read the four text boxes
Deposit = Val(txtDeposit.Text)
Interest = Val(txtInterest.Text)
Programim object-oriented Faqa 72
IntRate = Interest / 1200
Months = Val(txtMonths.Text)
Final = Val(txtFinal.Text)
‘Determine which box is blank
‘Compute that missing value and put in text box
If txtDeposit.Text = "" Then
‘Deposit missing
Deposit = Final / (((1 + IntRate) ^ Months - 1) / IntRate)
txtDeposit.Text = Format(Deposit, "#####0.00")
ElseIf txtInterest.Text = "" Then
‘Interest missing - requires iterative solution
IntNew = (Final / (0.5* Months * Deposit) - 1) / Months
Do
IntRate = IntNew
Fcn = (1 + IntRate) ^ Months - Final * IntRate / Deposit - 1
FcnD = Months * (1 + IntRate) ^ (Months - 1) - Final / Deposit
IntNew = IntRate - Fcn / FcnD
Loop Until Abs(IntNew - IntRate) < 0.00001 / 12
Interest = IntNew * 1200
txtInterest.Text = Format(Interest, "##0.00")
ElseIf txtMonths.Text = "" Then
‘Months missing
Months = Log(Final * IntRate / Deposit + 1) / Log(1 + IntRate)
txtMonths.Text = Format(Months, "###.0")
ElseIf txtFinal.Text = "" Then
Programim object-oriented Faqa 73
‘Final value missing
Final = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
txtFinal.Text = Format(Final, "#####0.00")
End If
End Sub
In this code. we first read the text information from all four text boxes and
based on which one is blank, compute the missing information and
display it in the corresponding text box. Solving for missing Deposit,
Months, or Final information is a straightforward manipulation of the
equation given in Example 2-2.
If the Interest value is missing, we have to solve an Mth-order polynomial
using something called Newton-Raphson iteration - a good example of
using a Do loop. Finding the Interest value is straightforward. What we
do is guess at what the interest is, compute a better guess (using Newton-
Raphson iteration), and repeat the process (loop) until the old guess and
the new guess are close to each other. You can see each step in the
code.
5. Testoni dhe ruani aplikacionin.
Programim object-oriented Faqa 74
Shembull 3-1
Computing a Mean and Standard Deviation
Develop an application that allows the user to input a sequence of numbers.
When done inputting the numbers, the program should compute the mean of
that sequence and the standard deviation. If N numbers are input, with the
ith number represented by xi, the formula for the mean ( ) is:
= ( )/ N
and to compute the standard deviation (s), take the square root of this
equation:
s2 = [N - ( )2]/[N(N - 1)]
The Greek sigmas in the above equations simply indicate that you add up all
the corresponding elements next to the sigma.
Programim object-oriented Faqa 75
Zgjidhja:
Form:
Vetitë:
Form frmStats:
Caption = Mean and Standard Deviation
CommandButton cmdExit:
Caption = E&xit
CommandButton cmdAccept:
Caption = &Accept Number
CommandButton cmdCompute:
Caption = &Compute
CommandButton cmdNew:
Caption = &New Sequence
Programim object-oriented Faqa 76
Label1
Label2
cmdAccept
cmdNew
Label6
Label4 lblStdDev
lblMean
cmdExit
cmdCompute
txtInput
lblNumber
TextBox txtInput:
FontName = MS Sans Serif
FontSize = 12
Label lblStdDev:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 12
Label Label6:
Caption = Standard Deviation
Label lblMean:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 12
Label Label4:
Caption = Mean
Label lblNumber:
Programim object-oriented Faqa 77
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 12
Label Label2:
Caption = Enter Number
Label Label1:
Caption = Number of Values
Kodi:
General Declarations:
Option Explicit
Dim NumValues As Integer
Dim SumX As Single
Dim SumX2 As Single
Const vbKeyMinus = 45
Const vbKeyDecPt = 46
Në ngjarjen Click të cmdAccept:
Private Sub cmdAccept_Click()
Dim Value As Single
Programim object-oriented Faqa 78
txtInput.SetFocus
NumValues = NumValues + 1
lblNumber.Caption = Str(NumValues)
‘Get number and sum number and number-squared
Value = Val(txtInput.Text)
SumX = SumX + Value
SumX2 = SumX2 + Value ^ 2
txtInput.Text = ""
End Sub
Në ngjarjen Click te cmdCompute:
Private Sub cmdCompute_Click()
Dim Mean As Single
Dim StdDev As Single
txtInput.SetFocus
‘Make sure there are at least two values
If NumValues < 2 Then
Beep
Exit Sub
End If
‘Compute mean
Mean = SumX / NumValues
lblMean.Caption = Str(Mean)
‘Compute standard deviation
Programim object-oriented Faqa 79
StdDev = Sqr((NumValues * SumX2 - SumX ^ 2) / (NumValues * (NumValues - 1)))
lblStdDev.Caption = Str(StdDev)
End Sub
Ne ngjarjen Click te cmdExit Click:
Private Sub cmdExit_Click()
End
End Sub
Ne ngjarjen Click te cmdNew:
Private Sub cmdNew_Click()
'Initialize all variables
txtInput.SetFocus
NumValues = 0
lblNumber.Caption = "0"
txtInput.Text = ""
lblMean.Caption = ""
lblStdDev.Caption = ""
SumX = 0
SumX2 = 0
End Sub
Programim object-oriented Faqa 80
Ne ngjarjen KeyPress te txtInput:
Private Sub txtInput_KeyPress(KeyAscii As Integer)
'Only allow numbers, minus sign, decimal point, backspace, return keys
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyMinus Or KeyAscii = vbKeyDecPt Or KeyAscii = vbKeyBack Then
Exit Sub
ElseIf KeyAscii = vbKeyReturn Then
Call cmdAccept_Click
Else
KeyAscii = 0
End If
End Sub
Programim object-oriented Faqa 81
Ushtrimi 3-2
Ushtrimi i mbledhjes së dy numrave të rastit
Shkruani një aplikim që gjeneron dy numra të rastit dhe kërkon nga
përdoruesi të gjejë shumën e tyre. Mundësoni dhe vlerësimin e përgjigjes si
dhe numërimin e përgjigjeve të sakta.
Zgjidhja:
Forma:
Vetitë:
Form frmAdd:
BorderStyle = 1 - Fixed Single
Caption = Mbledhja e dy numrave
CommandButton cmdNext:
Programim object-oriented Faqa 82
Label1
lblNum1
lblNum2
txtAnswer
lblMessage
cmdExitcmdNext
lblScore
Label4
Label2
Caption = &Pyetja tjetër
Enabled = False
CommandButton cmdExit:
Caption = &Dalje
TextBox txtAnswer:
FontName = Arial
FontSize = 48
MaxLength = 2
Label lblMessage:
Alignment = 2 - Center
BackColor = &H00FFFF00& (Cyan)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontBold = True
FontSize = 24
FontItalic = True
Label lblScore:
Alignment = 2 - Center
BackColor = &H0000FFFF& (Yellow)
BorderStyle = 1 - Fixed Single
Caption = 0
Programim object-oriented Faqa 83
FontName = Times New Roman
FontBold = True
FontSize = 36
Label Label1:
Alignment = 2 - Center
Caption = Pikët:
FontName = MS Sans Serif
FontSize = 18
Label Label4:
Alignment = 2 - Center
Caption = =
FontName = Arial
FontSize = 48
Label lblNum2:
Alignment = 2 - Center
FontName = Arial
FontSize = 48
Label Label2:
Alignment = 2 - Center
Caption = +
Programim object-oriented Faqa 84
FontName = Arial
FontSize = 48
Label lblNum1:
Alignment = 2 - Center
FontName = Arial
FontSize = 48
Kodi:
General Declarations:
Option Explicit
Dim Sum As Integer
Dim NumProb As Integer, NumRight As Integer
Ngjarja cmdExit Click:
Private Sub cmdExit_Click()
End
End Sub
Ngjarja cmdNext Click:
Private Sub cmdNext_Click()
'Gjeneron dy numra të rastit
Dim Number1 As Integer
Programim object-oriented Faqa 85
Dim Number2 As Integer
txtAnswer.Text = ""
lblMessage.Caption = ""
NumProb = NumProb + 1
'Gjenerimi
Number1 = Int(Rnd * 21)
Number2 = Int(Rnd * 21)
lblNum1.Caption = Format(Number1, "#0")
lblNum2.Caption = Format(Number2, "#0")
'Gjen shumen
Sum = Number1 + Number2
cmdNext.Enabled = False
txtAnswer.SetFocus
End Sub
Ngjarja Form Activate:
Private Sub Form_Activate()
Call cmdNext_Click
End Sub
Ngjarja Form Load:
Private Sub Form_Load()
Randomize
NumProb = 0
Programim object-oriented Faqa 86
NumRight = 0
End Sub
Ngjarja txtAnswer KeyPress:
Private Sub txtAnswer_KeyPress(KeyAscii As Integer)
Dim Ans As Integer
'Kontrollon per numrat dhe tastën Enter
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyBack Then
Exit Sub
ElseIf KeyAscii = vbKeyReturn Then
'Kontrollon përgjigjen
Ans = Val(txtAnswer.Text)
If Ans = Sum Then
NumRight = NumRight + 1
lblMessage.Caption = "E saktë!"
Else
lblMessage.Caption = "Përgjigja është: " + Format(Sum, "#0")
End If
lblScore.Caption = Format(100 * NumRight / NumProb, "##0")
cmdNext.Enabled = True
cmdNext.SetFocus
Else
KeyAscii = 0
Programim object-oriented Faqa 87
End If
End Sub
Programim object-oriented Faqa 88
4. Gjuha Visual Basic. Eksplorimi i kontrolleve të Toolbox –it të Visual Basic.
Në këtë kapitull do të shqyrtohet çdo kontroll i shiritit të kontrolleve (toolbox)
të Visual Basic. Do të rishqyrtohen disa kontrolle me të cilat ju jeni njohur në
kapitujt e parë, dhe një sërë kontrollesh të reja. Së pari do të njiheni me një
funksion shumë të rëndësishëm të Visual Basic.
Programim object-oriented Faqa 89
Dritarja e mesazhit (Message Box)
Një nga funksionet më të mira të Visual Basic është message box. Dritajra
e mesazhit afishon një mesazh, shpesh herë të shoqëruar me një ikone
(opsionale). Dritarja e mesazhit mund të ketë një ose disa butona. Përdoruesi
i përgjigjet kësaj dritareje duke klikuar në njërin nga butonat e saj.
Instruksioni që mundëson afishimin e një dritareje mesazhi ka sintaksën e
mëposhtëme dhe nuk kthen asnjë vlerë (ai thjeshtë afishon një mesazh në
një dritare):
MsgBox Mesazhi, Tipi, Titulli
ku
Mesazhi Teksti i mesazhit që do të afishohet
Tipi Tipi i dritares së mesazhit (do të shqyrtohet mëposhtë)
Title Teksti i afishuar në shiritin e titullit të dritares së mesazhit
Instruksioni MsgBox ka dhe trajtën e një funksioni që kthen një vlerë të tipit
integer (në varësi të butonit të shtypur nga përdoruesi).
Shembull:
Dim Pergjigje as Integer
Pergjigje = MsgBox(Mesazhi, Tipi, Titulli)
Argumenti Tipi formohet duke mbledhur katër vlerat që i korrespondojnë
butonave të afishuar, ikonës së shfaqur, butonit që i përgjigjjet
Programim object-oriented Faqa 90
automatikisht shtypjes së tastës ‘enter’, si dhe modalitetin e dritares së
mesazhit.
1. Komponenti i parë i Tipit specifikon butonat që do të afishohen:
Vlera Kuptimi Konstantja Simbolike
0 Vetëm butoni OKy vbOKOnly
1 Butonat OK/Cancel vbOKCancel
2 Butonat Abort/Retry/Ignore vbAbortRetryIgnore
3 Butonat Yes/No/Cancel vbYesNoCancel
4 Butonat Yes/No vbYesNo
5 Butonat Retry/Cancel vbRetryCancel
2. Komponenti i dytë i Tipit specifikon iconën që do të afishohet
në dritaren e mesazhit:
Vlera Kuptimi Konstantja Simbolike
0 Asnjë icon (None)
16 Ikona Kritike (X) vbCritical
32 Ikona Pyetëse (?) vbQuestion
48 Ikona Exclamation (!) vbExclamation
64 Ikona Informuese (i) vbInformation
Programim object-oriented Faqa 91
3. Komponenti i tretë i Tipit specifikon se cili do të jetë butoni
default (shtypja e enter-it është e njëjtë me klikimin në butonin
default):
Vlera Kuptimi Konstantja Simbolike
0 Butoni i parë default vbDefaultButton1
256 Butoni i dytë default vbDefaultButton2
512 Butoni i tretë default vbDefaultButton3
4. Komponenti i katërt dhe i fundit i Tipit specifikon modalitetin:
Vlera Kuptimi Konstantja Simbolike
0 Modal me aplikimin vbApplicationModal
4096 Modal me sistemin vbSystemModal
N.q.s. dritarja e mesazhit është Modal në lidhje me Aplikimin,
përdoruesi duhet t’i përgjigjet asaj dritareje para se të vazhdojë punën në
atë aplikim. N.q.s. dritarja e mesazhit është Modal në lidhje me
sistemin komunikimi me të gjithë aplikimet ndërpritet derisa përdoruesi
t’i përgjigjet kësaj dritareje.
Shihet se për secilin nga komponentët e Tipit, mund të përdoret si vlera
numerike ashtu dhe konstantja numerike. Megjithatë rekomandohet që të
përdoren këto të fundit në funksion të rritjes së lexueshmërisë së
aplikimit. P.sh. për përcaktimin e butonave të dritares, përdorimi i
Programim object-oriented Faqa 92
konstantes vbOKOnly është shumë më domethënës sesa përdorimi i
vlërës korresponduese 0 të saj.
Vlera e kthyer nga funksioni MsgBox lidhet me butonin e shtypur nga
përdoruesi:
Vlera Kuptimi Konstantja Simbolike
1 Shtypet butoni OK vbOK
2 Shtypet butoni Cancel vbCancel
3 Shtypet butoni Abort vbAbort
4 Shtypet butoni Retry vbRetry
5 Shtypet butoni Ignore vbIgnore
6 Shtypet butoni Yes vbYes
7 Shtypet butoni No vbNo
Shembull i përdorimit të dritares së mesazhit:
MsgBox “Ky është një shembull i një dritareje mesazhi”,
vbOKCancel + vbInformation, “Shembull”
Programim object-oriented Faqa 93
Metodat
Në shëmbujt e mëparshëm ju keni parë që çdo objekt krahas vetive dhe
ngjarjeve ka dhe metodat që nuk janë gjë tjetër veçse procedura ose
funksione që mundësojnë disa veprime të kryera mbi atë objekt.
Metodat aktivizohen vetëm gjatë ekzekutimit të programit, kështu që ato
janë pjesë vetëm e kodit të programit. Formati i aktivizimit të tyre është:
EmriObjektit.Metoda {lista opsionale (jo e detyrueshme) e
argumentave}
Programim object-oriented Faqa 94
Objekti Form
Objekti Form nuk është gjë tjetër veçse objekti kryesor ku ndërtohet
ndërfaqja e përdoruesit.
Disa nga vetitë kryesore të objektit Form:
Appearance Përcakton nëse dritarja paraqitet 3-D apo e
rrafshët.
BackColor Përcakton ngjyrën e sfondit të formës.
BorderStyle Përcakton nëse dritarja do të jetë apo jo e
ridimensionueshme.
Caption Përcakton titullin e shfaqur në shiritin e titullit të
dritares.
Enabled N.q.s. është True, lejon që formsi t’i përgjigjet
ngjarjeve të mouse-it dhe tastjerës.
Font Përcakton tipin e shkrimit, stilin dhe madhësinë.
ForeColor Ngjyra e shkrimit ose grafikës.
Picture Vendos një figurë në form.
Visible N.q.s është False, forma nuk është e dukshme.
Disa nga ngjarjet kryesore të objektit Form:
Activate Ngjarja Form_Activate ndodh kur një form bëhet
aktive.
Programim object-oriented Faqa 95
Click Ngjarja Form_Click ndodh kur përdoruesi klikon në
form.
DblClick Ngjarja Form_DblClick ndodh kur përdoruesi klikon
dy herë në form.
Load Ngjarja Form_Load ndodh në momentin e
ngarkimit të formës. Është një vend shumë i
përshtatshëm për të inicializuar variablat global të
formë dhe për të vendosur vetitë që përcaktohen
gjatë ekzekutimit të programit.
Disa nga metodat kryesore të objektit Form:
Cls Pastron të gjithë tekset ose grafikët e vizatuar në
një form. Nuk ka ndikim tek objektet e vendosur
në form.
Print Afishon një tekst në form.
Shembuj:
frmShembull.Cls ' pastron formën
frmShembull.Print "Afishon këtë mesazh në form"
Programim object-oriented Faqa 96
Kontrolli Command Button
Ju jeni njohur dhe më parë më kontrollin command button. Ai mbase është
kontrolli më i përdorshëm. Përdoret për të filluar, ndërprerë ose përfunduar
një proçes të caktuar.
Disa nga vetitë më të rëndësishme të kontrollit Command Button:
Appearance Përcakton nëse butoni paraqitet 3-D apo i
rrafshët.
Cancel Lejon aktivizim e butonit me shtypjen e tastës Esc
(vetëm një buton në një formë mund ta ketë këtë
veti True).
Caption Teksti i afishuar në buton.
Default Lejon aktivizim e butonit me shtypjen e tastës
Enter (vetëm një buton në një formë mund ta
ketë këtë veti True).
Font Përcakton tipin e shkrimit, stilin dhe madhësinë.
Ngjarja më e rëndësishme e kontrollit Command Button:
Click Ndodh kur përdoruesi klikon mbi buton apo kur
shtyp tastat e zgjedhura për aktivizim e tij.
Programim object-oriented Faqa 97
Kontrolli Label Boxe
Kontrolli label box përdoret për të afishuar një tekst që përdoruesi nuk
mund ta modifikojë gjatë kohës së ekzekutimit të programit.
Disa nga vetitë më të rëndësishme të kontrollit Label:
Alignment Orjenton tekstin e afishuar në lidhje me konturin.
Appearance Përcakton nëse label paraqitet 3-D apo e rrafshët.
AutoSize N.q.s. është True, label ridimensionohet
automatikisht për të afishuar të gjithe përmbajtjen
e tij, në të kundërt nëse kjo vlerë është False
përmasat e label-it mbeten ato që janë përcaktuar
në momentin e ndërtimit të aplikimit, pavarësisht
nëse teksti shfaqet apo jo i plotë.
BorderStyle Përcakton tipin e konturit.
Caption Teksi i afishuar në label.
Font Përcakton tipin e shkrimit, stilin dhe madhësinë.
Programim object-oriented Faqa 98
WordWrap Funksionon në bashkëveprim me vetinë AutoSize.
N.q.s. AutoSize = True, WordWrap = True,
atëherë teksti do të “thyhet” në disa rreshta dhe
label-i do të zgjerohet vertikalisht për të shfaqur
të plotë të gjithë përmbajtjen e tij. N.q.s. AutoSize
= True, WordWrap = False, atëherë teksti
afishohet në një rresht dhe label-i zgjerohet
horizontalisht për të shfaqur të plotë përmbajtjen
e tij. N.q.s. AutoSize = False, teksi nuk “thyhet”
pavarësisht vlerës së vetisë WordWrap.
Ngjarjet e kontrollit Label:
Click Ndodh kur përdoruesi klikon mbi label.
DblClick Ndodh kur përdoruesi klikon dy herë mbi label.
Programim object-oriented Faqa 99
Text Boxes
Kontrolli text box përdoret për të afishuar një informacion të përcaktuar në
momentit e ndërtimit të aplikimit (design time), të shtypur nga përdoruesi
gjatë ekzekutimit të programit, ose të përcaktuar me kod. Teksti i afishuar
mund të modifikohet.
Disa nga vetitë më të rëndësishme të kontrollit Text Box:
Appearance Përcakton nëse text box-i paraqitet 3-D apo i
rrafshët.
BorderStyle Tipi i konturit.
Font Përcakton tipin e shkrimit, stilin dhe madhësinë.
MaxLength Përcakton numrin maksimal të karaktereve që
mund të pranojë text box-i. (Vlera 0 përdoret kur
nuk ka kufizime).
MultiLine Specifikon nëse text box-i do ta afishojë
informacionin në një rresht apo në shumë rreshta.
PasswordChar Fsheh tekstin dhe për çdo karakter afishon
karakterin e zgjdhur.
ScrollBars Specifikon tipin e ashensorëve.
SelLength Numri i karaktereve të zgjdhura (e vlefshme
vetëm gjatë ekzekutimit të programit).
Programim object-oriented Faqa 100
SelStart Pozicioni i karakterit të parë të zgjedhur (e
vlefshme vetëm gjatë ekzekutimit të programit).
SelText Teksi i zgjedhur (e vlefshme vetëm gjatë
ekzekutimit të programit).
Tag Ruan një string.
Text Teksti i afishuar.
Ngjarjet më të rëndësishme të Text Box-it:
Change Ndodh sa herë që ndryshon vetia Text.
LostFocus Ndodh kur kontrolli largohet nga text box-i. është
vendi më i mirë për të kontrolluar përmbajtjen e
text box–it pasi përfundon modifikimi i tij.
KeyPress Ndodh sa herë që shtypet një tastë ndërkohë që
jeni të pozicionuar në text box. Përdoret gjerëisht
për kontrollin e tastave të shtypura, siç e patë në
kapitullin e mëpashëm.
Një metodë e rëndësishme e kontrollit Text Box:
SetFocus Vendos kursorin në text box-in e zgjedhur.
Programim object-oriented Faqa 101
Shembull
txtShembull.SetFocus 'çon kursorin në text box-in me emër
txtShembull
Programim object-oriented Faqa 102
Shembull 4-1
Fjalëkalimi
1. Hapni një projekt të ri. Qëllimi i këtij projekti është të pyesë përdoruesin
për fjalëkalimin e aplikimit. Nëse përgjigja e dhënë nga përdoruesi është e
saktë afishohet një dritare mesazhi, në të kundërt përdoruesi ftohet të
provojë përsëri.
2. Vendosni në form dy butona, një label dhe një text box, siç paraqiten në
figurën e mëposhtëme:
3. Vendosni vetitë e këtyre kontrolleve si më poshtë:
Form1:
BorderStyle 1-Fixed Single
Caption Fjalëkalimi
Name frmPassword
Programim object-oriented Faqa 103
Label1:
Alignment 2-Center
BorderStyle 1-Fixed Single
Caption Ju lutem jepni fjalëkalimin:
FontSize 10
FontStyle Bold
Text1:
FontSize 14
FontStyle Regular
Name txtPassword
PasswordChar *
Tag [Fjalëkalimi_juaj]
Text [Blank]
Programim object-oriented Faqa 104
Command1:
Caption &Kontrollo
Default True
Name cmdValid
Command2:
Cancel True
Caption &Dalje
Name cmdExit
Tashmë forma do të ketë këtë pamje:
4. Shkruani kodin e mëposhtëm në ngjarjen cmdValid_Click.
Private Sub cmdValid_Click()
'Kjo procedure kontrollon fjalëkalimin
Dim Response As Integer
If txtPassword.Text = txtPassword.Tag Then
Programim object-oriented Faqa 105
'Nese eshte korrekt afishon kete mesazh
MsgBox "Fjalekalimi i sakte!", vbOKOnly + vbExclamation, "Hyrje e garantuar"
Else
'Nese eshte i pasakte ftoheni te provoni perseri
Response = MsgBox("Fjalekalim i pasakte", vbRetryCancel + vbCritical, "Ndalohet hyrja")
If Response = vbRetry Then
txtPassword.SelStart = 0
txtPassword.SelLength = Len(txtPassword.Text)
Else
End
End If
End If
txtPassword.SetFocus
End Sub
Ky kod kontrollon saktësinë e fjalëkalimit. Nëse ai është i saktë afishon një
mesazh pranimi, në të kundërt afishon një dritare mesazhi që me ndihmën e
butonit Retry, fton përdoruesin të tentojë sërisht. Nëse përdoruesi zgjedh të
tentojë nga e para procedura përsëritet, në të kundërt (nëse ka zgjedhur
butonin Cancel), programi përfundon. Përdorimi i funksioneve SelLength
dhe SelStart bëhet për të zgjedhur fjalëkalimin në rastin kur ai nuk është i
saktë në mënyrë që përdoruesi të fillojë të shtypë direkt fjalëkalimin e ri pa
qënë nevoja të fshijë të vjetrin (ai fshihet automatikisht sapo përdoruesi
fillon të shtypë).
5. Kodi në ngjarjen Form_Activate.
Programim object-oriented Faqa 106
Private Sub Form_Activate()
txtPassword.SetFocus
End Sub
6. Kodi në ngjarjen cmdExit_ Click.
Private Sub cmdExit_Click()
End
End Sub
7. Ekzekutoni aplikimin. Provoni të dy rastet, fjalëkalimin e saktë (kujdes, ka
dallim ndërmjet shkronjave të vogla dhe të mëdha), si dhe fjalëkalimin e
pasaktë. Regjistroni projektin.
Kërkesë
Përcaktoni një konstante MAX_PROVA = 3, dhe modifikoni kodin në
mënyrë që të mos lejohen më shumë se MAX_PROVA tentativa për të
dhënë fjalëkalimin e saktë. Pas provës finale, njoftoni përdoruesin që ai
nuk mund të përdorë më programin.
Programim object-oriented Faqa 107
Check Box-et
Check box-et ofrojnë një mënyrë për të zgjedhur një ose disa vlera nga një
listë mundësish potenciale. Nga një grup vlerash mund të mos zgjidhet
asnjë, një, disa ose të gjitha.
Disa nga vetitë kryesore të Check Box:
Caption Përcakton tekstin që afishin check box-i.
Font Cakton tipin e shkrimit, stilin dhe madhësinë.
Value Tregon nëse check box është i pazgjedhur (0,
vbUnchecked), i zgjedhur (1, vbChecked), ose jo
aktiv (2, vbGrayed).
Ngjarja kryesore e Check Box:
Click Ndodh kur klikohet një check box. Vetia Value
ndryshohet automatikisht nga Visual Basic.
Programim object-oriented Faqa 108
Option Buttons
Option buttons ofrojnë mundësinë e zgjedhjes së një mundësie të vetëm
nga një grup mundësishë potenciale. Butonat opsionale funksionojnë në
grupe, në të cilat vetëm një buton mund të jetë i zgjedhur (të ketë vlerën
True).
Disa nga vetitë kryesore të Option Button:
Caption Përcakton tekstin që afishin option button.
Font Cakton tipin e shkrimit, stilin dhe madhësinë.
Value Përcakton nëse butoni është i zgjedhur (True) ose
jo (False). Vetëm një buton mund të zgjidhet në
një grup. Një buton në një grup duhet të
inicializohet gjithnjë me vlerën True që në
momentin e ndërtimit të aplikimit (design time).
Ngjarja kryesore e Option Button:
Click Ndodh kur klikohet një option button. Vetia
Value ndryshohet automatikisht nga Visual
Basic.
Programim object-oriented Faqa 109
Vektorët
Deri tani jeni njohur me variabla normalë, ku çdo variabël ka emrin e vet
unik. Visual Basic ofron mundësinë e punës me variabla shumë
dimensionalë, të quajtur ndryshe vektorë. Për momentin do të përdorim
vektorët një dimensional
Vektorët deklarohen në mënyrë identike si variablat e zakonshëm. Për
shëmbull, për të deklaruar vektorin me emrin 'Elementet', me 10 elementë,
bëhet ky deklarim në nivel procedure:
Dim Elementet(9) as Integer
Nëse dëshironi që elementët e vektorit të ruajnë vlerat edhe kur përfundon
ekzekutimi i procedurës ku ato janë deklaruar, për deklarimin e tij përdoret
fjala çelës Static:
Static Elementet(9) as Integer
Në nivel form-e ose moduli, në seksionin ‘general declarations’ të dritares
së kodit, deklarimi bëhet në këtë mënyrë:
Dim Elementet(9) as Integer
Në nivel moduli për të deklaruar vektorin global:
Global Elementet(9) as Integer
Indeksi i një vektori fillon nga 0 deri në vlerën që është përdorur në
momentin e deklarimit. Për shembull, vektori Elementet në shembullin e
mësipërm ka dhjetë element, Elementet(0) deri tek Elementet(9). Përdorimi
Programim object-oriented Faqa 110
i vektorëve është i njëjtë me përdorimin e variablave të zakonshëm, me
përjashtim të faktit që krahas emrit të vektorit duhet të përdoret patjetër
dhe indeksi i futur në kllapa. Për shëmbull, për të vendosur vlerën 7 në
elementin Elementet(5), duhet instruksioni i mëposhtëm:
Elementet(5) = 7
Programim object-oriented Faqa 111
Vektorët e kontrolleve
Për disa kontrolle, në varësi të aplikimit është shumë e dobishme krijimi i
vektorëve të kontrolleve. Për shembull, butonat opsionalë përgjithësisht
grupohen në vektorë.
Vektorët e kontrolleve janë një mënyrë shumë e përshtatshme për të trajtuar
grupet e kontrolleve që kanë funksion të ngjashëm. Të gjitha ngjarjet e një
kontrolli të vetëm tashme i takojnë të gjitha kontrolleve të vektorit, me
shtesën e një argumenti index që identifikon indeksin e kontrollit në vektor.
Në këtë mënyrë. Në vend që të shkruhen procedura individuale për secilin
kontroll, në rastin e vektorëve të kontrolleve shkruhet një procedurë e vetme
për të gjithë kontrollet.
Një tjetër avantazh i vektorëve të kontrolleve është krijimi dhe fshirja e tyre
gjatë kohës së ekzekutimit të programit, gjë që s’mund të bëhet me
kontrollet që nuk janë pjesë e një vektori kontrollesh. Për këtë qëllim
shërbejnë komandat Load dhe Unload.
Dy rrugët e krijimit të vektorëve të kontrolleve:
1. Krijoni një kontroll dhe përcaktoni të gjitha vetitë e tij. Kopjojeni atë me
ndihmën e komondës Copy dhe më pas vendoseni kopjen në form me
ndihmën e komandës Paste. Visual Basic me ndihmën e një dritareje
dialogu do ju pyes nëse dëshironi të krijoni një vektor kontrollesh.
Përgjigjuni Yes dhe vektori do të krijohet.
2. Krijoni të gjithë kontrollet që dëshironi të keni në vektor. Vendosini
emrin që dëshironi në kontrollin e parë. Më pas vendosini të njëjtin
emër edhe kontrollit të dytë. Visual Basic do ju pyes nëse dëshironi të
Programim object-oriented Faqa 112
krijoni një vektor kontrollesh. Përgjigjuni Yes. Pasi të jetë krijuar vektori
vendosini të njëjtin emër të gjithë kontrolleve.
Pasi është krijuar një vektor kontrollesh, elementëve të këtij vektori i
referohemi me emrin dhe indeksin e tyre. P.sh. për të përcaktuar vetinë
Caption të elementit me indeks 6 të një vektori label-ash me emrin
lblExample, kemi:
lblExample(6).Caption = “Ky është një shembull”
Programim object-oriented Faqa 113
Frame-t
Kemi parë që butonat opsionalë dhe check box-et funksionojnë në grup.
Frame është kontrolli që bën pikërisht këtë grupim.
Për të grupuar kontrollet në një frame, së pari vendosni frame në form. Më
pas kontrollet e të njëjtit grup vendosini brenda frame-it. Kjo ju lejon që të
levizni kontrollet së bashku me frame-in. Pasi një kontroll është vendosur
brenda një frame-i ai mund të bëhet “copy-paste” në të për të krijur një
vektor kontrollesh.
Frame-et përcaktojë mënyrën se si punojnë butonat opsionalë. Butonat
opsionalë brenda një frame funksionojnë si një grup, pavarësisht butonave
opsionalë në frame-t e tjera. Butonat opsionalë që mund të jenë vendosur
drejtëpërsëdrejti në form, funksionojnë si një tjetër grup i pavarur. Kjo për
faktin e thjeshtë se form-si është në vetëvete një ‘frame”.
Është shumë e rëndësishme të vini re se grupet e ndryshme të butonave
opsionalë janë pikërisht të ndryshme jo për shkak se mund të kenë emra të
ndryshëm por pikërisht për faktin se bëjnë pjesë në frame të ndryshme.
Disa nga vetitë kryesore të Frame-it:
Caption Informacioni i afishuar në krye të frame-it.
Font Përcakton tipin, stilin dhe madhësinë e shkrimit.
Programim object-oriented Faqa 114
Shembull 4-2
Porosite e picave
1. Hapni një projekt të ri. Do të ndërtoni një form ku me ndihmën e disa
check box-eve dhe butonave opsionale do të bëhet e mundur porosia e
një pice.
2. Vendosni në form tre frame. Në të parën vendosni tre butona opsionalë,
në të dytën dy butona opsionalë dhe në të tretën tre check box-e.
Vendosni në form gjithashtu dy butona opsionalë dhe dy butona
(command buttons). Forma të ketë pamjen e mëposhtëme.
3. Vendosni këto veti për formën dhe kontrollet e vendosur në të.
Form1:
BorderStyle 1-Fixed Single
Programim object-oriented Faqa 115
Caption Porosite e picave
Name frmPizza
Frame1:
Caption Madhesia
Frame2:
Caption Trashesia
Frame3
Caption Lloji
Option1:
Caption E Vogel
Name optSize
Value True
Option2:
Caption E mesme
Name optSize (yes, create a control array)
Option3:
Caption E madhe
Name optSize
Option4:
Caption E holle
Name optCrust
Programim object-oriented Faqa 116
Value True
Option5:
Caption E trashe
Name optCrust (yes, create a control array)
Option6:
Caption Ne restorant
Name optWhere
Value True
Option7:
Caption Ne shtepi
Name optWhere (yes, create a control array)
Check1:
Caption Kater djathra
Name chkTop
Check2:
Caption Kapricoze
Name chkTop (yes, create a control array)
Check3:
Caption Kater stinet
Name chkTop
Check4:
Programim object-oriented Faqa 117
Caption Sallam, proshute
Name chkTop
Check5:
Caption Me kerpurdha
Name chkTop
Check6:
Caption Margarita
Name chkTop
Command1:
Caption &Krijo picen
Name cmdBuild
Command2:
Caption &Dalje
Name cmdExit
Programim object-oriented Faqa 118
Tashmë Forma duhet të ketë këtë pamje:
4. Deklaroni këto variabla në zonën general declarations:
Option Explicit
Dim PizzaSize As String
Dim PizzaCrust As String
Dim PizzaWhere As String
Kjo bën që variablat që kanë lidhje me madhësinë, trashësinë dhe
vendndodhjen të jenë variabla globalë në form.
5. Shkruani kodin e mëposhtëm në procedurën Form_Load. Ai inicializon
madhësinë, trashësinë dhe vendngrënien.
Programim object-oriented Faqa 119
Private Sub Form_Load()
'Inicializon parametrat e pices
PizzaSize = "E vogël"
PizzaCrust = "E hollë"
PizzaWhere = "Ne restorant"
End Sub
Këtu variablat global inicializohen me vlerat e tyre fillestare në varësi të
vlerave fillestare të butonave opsionalë.
6. Shtoni kodin e mëposhtëm në ngjarjet Click të vektorëve të kontrolleve të
butonave opsionalë. Vini re përdorimin e variablit Index:
Private Sub optSize_Click(Index As Integer)
‘Lexon madhësinë e picës
PizzaSize = optSize(Index).Caption
End Sub
Private Sub optCrust_Click(Index As Integer)
‘Lexon trashësinë e picës
PizzaCrust = optCrust(Index).Caption
End Sub
Private Sub optWhere_Click(Index As Integer)
‘Lexon vendngrenien
PizzaWhere = optWhere(Index).Caption
Programim object-oriented Faqa 120
End Sub
Në secilën nga këto procedura, kur klikohet një buton opsional, vlera
korresponduese e vetisë Caption të tij shkon në variablin përkatës.
7. Shkruani kodin e mëposhtëm në ngjarjen cmdBuild_Click.
Private Sub cmdBuild_Click()
'Kjo procedure nderton nje mesazh që afishon preferencat tuaj mbi picen e zgjedhur
Dim Message As String
Dim I As Integer
Message = PizzaWhere + vbCr
Message = Message + PizzaSize + " Pizza" + vbCr
Message = Message + PizzaCrust + vbCr
For I = 0 To 5
If chkTop(I).Value = vbChecked Then Message = Message + chkTop(I).Caption + vbCr
Next I
MsgBox Message, vbOKOnly, "Pica juaj"
End Sub
Kjo pjesë kodi formon nje string si bashkim të stringjeve që përfaqësojnë
madhësinë e picës, trashësinë e saj dhe vendngrënien (vbCr është
konstantja simbolike që përfaqëson ‘kalimin në krye të rreshtit të ri’). Më pas
ky kod nëpërmjet një cikli nëpër të gjashtë check box-et që përfaqësojnë
llojin e picës, shton në mesazhin e mësipërm dhe tipet e picave të
preferuara. Më pas me ndihmën e funksionit msgbox afishohet në ekran
porosia.
Programim object-oriented Faqa 121
8. Kodi në ngjarjen cmdExit_Click.
Private Sub cmdExit_Click()
End
End Sub
9. Ekzekutoni aplikimin. Vini re mesazhet e ndryshme që afishon si pasojë e
zgjedhjeve të ndryshme të bëra në form. Regjistroni projektin.
10. Bëni këto modifikime në program:
A. Shtoni një buton të ri që inicializon të gjithë elementët e formës në
vlerat e tyre fillestare. Duhet të riinicializoni tre variablat globalë, të
pastroni të gjithë check box-et dhe të vendosni tre grupet e
butonave opsionalë në vlerat e tyre fillestare.
B. Modifikoni kodin në mënyrë që nëse nuk zgjidhet asnjë tip pice, të
afishohet në mesazh tipi i picës “Margarita”.
Programim object-oriented Faqa 122
List Box-et
Një list box afishon një listë elementësh nga të cilët përdoruesit mund të
zgjedhin një ose më shumë elementë. Nëse numri i elementëve të listës e
kalon numrin e elementëve që mund të paraqesë listë box-i, atëherë shfaqet
automatikish një ashensor vertikal.
Disa nga vetitë e kontrollit List Box:
Appearance Përcakton nëse text box-i paraqitet 3-D apo i
rrafshët.
List Vektori i elementëve të list box-it.
ListCount Numri i elementëve të listës.
ListIndex Numri i elementit të fundit që është zgjedhur në
listë. N.q.s. asnjë element nuk është zgjedhur
atëherë ListIndex = -1.
MultiSelect Përcakton numrin e elementëve që mund të
zgjidhen (0-vetëm një element, 1-shumë elementë
njëherësh, 2-grup elementësh).
Selected Array with elements set equal to True or False,
depending on whether corresponding list item is
selected.
Programim object-oriented Faqa 123
Sorted True do të thotë se elementët paraqiten të
renditur në rendin rritës ose zbritës të bazuar në
kodet 'Ascii', në të kundërt elementët paraqiten
në rradhën që janë shtuar.
Text Teksti i elementit të fundit të zgjedhur.
Ngjarjet kryesore të List Box:
Click Ngjarje që ndodh kur klikohet një element i listë.
DblClick Ngjarje që ndodh kur klikohet dy herë një element
i listë.
Disa nga metodat e List Box:
AddItem Mundëson shtimin e një elementi në listë.
Clear Fshin të gjithë elementët e një liste.
RemoveItem Fshin nga lista elementin e identifikuar me
indeksin e përcaktuar në listën e argumentave të
metodës.
Shembull:
lstExample.AddItem "Ky është një element i listës" 'shton
stringun në listë
lstExample.Clear 'fshin elementët nga lista
Programim object-oriented Faqa 124
lstExample.RemoveItem 4 'fshin nga lista elementin
lstExample.List(4)
Elementët e një liste zakonisht inicializohen në procedurën Form_Load. Është
e këshillueshme që gjithnjë para momentit të inicializimit lista të pastrohet
me ndihmën e metodës Clear.
Programim object-oriented Faqa 125
Combo Box-et
Kontrolli combo box është i ngjashëm me kontrollin list box. Ndryshimi
qëndron në faktin që një combo box përmban një text box në krye të listës
dhe lejon zgjedhjen vetëm të një elementi. Në disa raste nëse asnjë nga
elementët e combo box nuk kënaq kërkesat e përdoruesit, ai mund të shtypë
vetë vlerën e duhur.
Disa nga vetitë e Combo Box:
Vetitë e Combo box janë shumë të ngjashme me ato të list box, me
përjashtim të vetisë MultiSelect që nuk ekziston tek Combo box (meqe nuk
ekziston mundësia e një zgjdhje të shumëfishtë) dhe shtimit të vetisë Style
(që mundëson shkrimin e një elementi që nuk ekziston në combo).
Appearance Përcakton nëse combo box-i paraqitet 3-D apo i
rrafshët.
List Vektori i elementëve të combo box-it.
ListCount Numri i elementëve të combo box-it.
ListIndex Numri i elementit të fundit që është zgjedhur në
combo box. N.q.s. asnjë element nuk është
zgjedhur atëherë ListIndex = -1.
Style Përcakton stilin e combo box.
Programim object-oriented Faqa 126
Style = 0, Dropdown combo; përdoruesi mund të
ndryshojë zgjedhjen.
Style = 1, Simple combo; përdoruesi mund të
ndryshojë zgjedhjen.
Style = 2, Dropdown combo; përdoruesi nuk mund
të ndryshojë zgjedhjen.
Sorted True do të thotë se elementët paraqiten të
renditur në rendin rritës ose zbritës të bazuar në
kodet 'Ascii', në të kundërt elementët paraqiten
në rradhën që janë shtuar.
Text Teksti i elementit të fundit të zgjedhur.
Disa nga ngjarjet e Combo Box:
Click Ngjarje që ndodh kur klikohet një element i listë.
DblClick Ngjarje që ndodh kur klikohet dy herë një element
i listë.
Metodat kryesore të Combo Box:
AddItem Mundëson shtimin e një elementi në combo box.
Clear Fshin të gjithë elementët e një combo box-i.
RemoveItem Fshin nga combo elementin e identifikuar me
indeksin e përcaktuar në listën e argumentave të
metodës.
Programim object-oriented Faqa 127
Shembull:
cboExample.AddItem "Ky është një element i combos" 'shton një
element
cboExample.Clear 'pastron the comb box-
in
cboExample.RemoveItem 4 'heq elementin cboExample.List(4) nga
combo box
Programim object-oriented Faqa 128
Shembull 4-3
Fluturimet ajrore
1. Hapni një projekt të ri. Në këtë shembull ju do të zgjidhni destinacionin ku
do të shkoni, pozicionin në avion dhe ushqimin e preferuar.
2. Vendosni në form një list box, dy combo box-e, tre label box dhe dy
command buttons. Forma duhet të ketë një pamje të tillë:
3. Vetitë e formës dhe të objekteve:
Form1:
BorderStyle 1-Fixed Single
Caption Fluturimi ajror
Name frmFlight
Programim object-oriented Faqa 129
List1:
Name lstCities
Sorted True
Combo1:
Name cboSeat
Style 2-Dropdown List
Combo2:
Name cboMeal
Style 1-Simple
Text [Bosh]
(Pas përcaktimit të vetive për këtë combo box, ridimensionojeni atë në
mënyrë që të paraqesë 4-5 elemente.)
Label1:
Caption Destinacioni
Label2:
Caption Pozicioni
Label3:
Caption Ushqimi preferuar
Command1:
Programim object-oriented Faqa 130
Caption &Vendos
Name cmdAssign
Command2:
Caption &Dalje
Name cmdExit
Forma duhet të ketë një pamje të tillë:
Programim object-oriented Faqa 131
4. Kodi në procedurën Form_Load:
Private Sub Form_Load()
‘Shton ne liste emrat e qyteteve
lstCities.Clear
lstCities.AddItem "Rome"
lstCities.AddItem "Milano"
lstCities.AddItem "Bolonja"
lstCities.AddItem "Torino"
lstCities.AddItem "Firence"
lstCities.AddItem "Paris"
lstCities.AddItem "Londer"
lstCities.AddItem "Viene"
lstCities.AddItem "Mynih"
lstCities.AddItem "Athine"
lstCities.AddItem "Toronto"
lstCities.AddItem "Nju Jork"
lstCities.ListIndex = 0
‘Tipet e karrikeve
cboSeat.AddItem "Korridor"
cboSeat.AddItem "Mes"
cboSeat.AddItem "Dritare"
cboSeat.ListIndex = 0
‘Tipet e ushqimeve
Programim object-oriented Faqa 132
cboMeal.AddItem "Pule"
cboMeal.AddItem "Mish"
cboMeal.AddItem "Vegjetarian"
cboMeal.AddItem "Fruta"
cboMeal.Text = "Asnje preference"
End Sub
Kjo pjesë kodi bën inicializimin dhe mbushjen e listës dhe combove me vlerat
përkatëse.
5. Kodi në ngjarjen cmdAssign_Click:
Private Sub cmdAssign_Click()
‘Nderton mesazhin qe do te afishohet
Dim Message As String
Message = "Destinacioni: " + lstCities.Text + vbCr
Message = Message + "Pozicioni: " + cboSeat.Text + vbCr
Message = Message + "Ushqimi: " + cboMeal.Text + vbCr
MsgBox Message, vbOKOnly + vbInformation, "Preferencat tuaja"
End Sub
Kur klikohet në butonin Assign, kodi i mësipërm formon një mesazh të cilin e
afishon me ndihmën e funksionit msgbox. Mesazhi formohet duke bashkuar
elementët e zgjedhur në listen e destinacioneve (lstCities), listen e
pozicionit (cboSeat), dhe në atë të ushqimit të preferuar (cboMeal).
6. Kodi në ngjarjen cmdExit_Click:
Programim object-oriented Faqa 133
Private Sub cmdExit_Click()
End
End Sub
7. Ekzekutoni aplikimin. Regjistroni projektin.
Programim object-oriented Faqa 134
Ushtrim 4
Dritarja e të dhënave të klientëve
Një dyqan sportiv do të ndërtojë një dritare ku të plotësojë të dhënat e
klientëve të tij. Informacioni i kërkuar është:
1. Emri
2. Mosha
3. Qyteti
4. Gjinia
5. Aktiviteti (Vrapim, Ecje sportive, Ciklizem, Not, Tenis, Patinazh)
6. Niveli (Ekstrem, I avancuar, Mesatar ose Fillestar)
Ndërtoni një dritare ku të regjistrohet vetem Emri, mosha dhe qyteti nëse
për këtë të fundit nuk do të përdori combo box (ku mund edhe të shkruhet).
Të gjithë të dhënat e tjera të plotësohen me ndihmën e butonave opsionale
dhe të check box. Kur informacioni për një klient është i plotë të shfaqet një
mesazh që përmbledh të gjithë informacionin. Psh:
Zgjidhja:
Programim object-oriented Faqa 135
Form:
Properties:
Form frmCustomer:
BorderStyle = 1 - Fixed Single
Caption = Profili i klientit
CommandButton cmdExit:
Caption = &Dalje
Frame Frame3:
Caption = Qyteti
Programim object-oriented Faqa 136
cmdSho
cmdExit
cboCity
txtAge
Frame4 optLevelchkActFrame2
Frame1
optSex
Frame3
Label1
txtName
cmdNew
Label2
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
ComboBox cboCity:
Sorted = True
Style = 1 - Simple Combo
CommandButton cmdNew:
Caption = &Profil i ri
CommandButton cmdShow:
Caption = &Afisho profil
Frame Frame4:
Caption = Niveli atletik
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
OptionButton optLevel:
Caption = Fillestar
Index = 3
OptionButton optLevel:
Programim object-oriented Faqa 137
Caption = I Mesem
Index = 2
Value = True
OptionButton optLevel:
Caption = I Avancuar
Index = 1
OptionButton optLevel:
Caption = Ekstrem
Index = 0
Frame Frame1:
Caption = Gjinia
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
OptionButton optSex:
Caption = Femer
Index = 1
OptionButton optSex:
Caption = Mashkull
Index = 0
Programim object-oriented Faqa 138
Value = True
Frame Frame2:
Caption = Aktivitetet
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
CheckBox chkAct:
Caption = Patinazh
Index = 5
CheckBox chkAct:
Caption = Tenis
Index = 4
CheckBox chkAct:
Caption = Not
Index = 3
CheckBox chkAct:
Caption = Ciklizem
Index = 2
CheckBox chkAct:
Caption = Ecje sportive
Programim object-oriented Faqa 139
Index = 1
CheckBox chkAct:
Caption = Vrapim
Index = 0
TextBox txtName:
FontName = MS Sans Serif
FontSize = 12
Label Label1:
Caption = Emri
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
TextBox txtAge:
FontName = MS Sans Serif
FontSize = 12
Label Label2:
Caption = Mosha
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
Programim object-oriented Faqa 140
FontItalic = True
Kodi:
General Declarations:
Option Explicit
Dim Activity As String
Ngjarja cmdExit Click:
Private Sub cmdExit_Click()
End
End Sub
Programim object-oriented Faqa 141
Ngjarja cmdNew Click:
Private Sub cmdNew_Click()
'Boshatis fushat emri dhe mosha dhe inicializon check box-et
Dim I As Integer
txtName.Text = ""
txtAge.Text = ""
For I = 0 To 5
chkAct(I).Value = vbUnchecked
Next I
End Sub
Ngjarja cmdShow Click:
Private Sub cmdShow_Click()
Dim NoAct As Integer, I As Integer
Dim Msg As String, Pronoun As String
'Sigurohet qe emri eshte plotesuar
If txtName.Text = "" Then
MsgBox "Ju lutem plotesoni emrin.", vbOKOnly + vbCritical, "Mungon emri"
Exit Sub
End If
'Sigurohet qe mosha eshte plotesuar
If txtAge.Text = "" Then
Programim object-oriented Faqa 142
MsgBox "Ju lutem plotesoni moshen.", vbOKOnly + vbCritical, "Mungon mosha"
Exit Sub
End If
'Krijon profilin nisur nga te dhenat
Msg = txtName.Text + " eshte " + Str$(txtAge.Text) + " vjec." + vbCr
If optSex(0).Value = True Then Pronoun = "Ai " Else Pronoun = "Ajo "
Msg = Msg + Pronoun + "jeton ne " + cboCity.Text + "." + vbCr
Msg = Msg + Pronoun + "eshte sportist i nivelit "
Msg = Msg + Activity + vbCr
NoAct = 0
For I = 0 To 5
If chkAct(I).Value = vbChecked Then NoAct = NoAct + 1
Next I
If NoAct > 0 Then
Msg = Msg + "Aktivitetet qe ushtron jane:" + vbCr
For I = 0 To 5
If chkAct(I).Value = vbChecked Then Msg = Msg + String$(10, 32) + chkAct(I).Caption + vbCr
Next I
Else
Msg = Msg + vbCr
End If
MsgBox Msg, vbOKOnly, "Profili i klientit"
Programim object-oriented Faqa 143
End Sub
Form Load Event:
Private Sub Form_Load()
'Ngarkon combo box e qyteteve me disa emra qytetesh
cboCity.AddItem "Tirane"
cboCity.Text = "Durres"
cboCity.AddItem "Shkoder"
cboCity.AddItem "Elbasan"
cboCity.AddItem "Berat"
cboCity.AddItem "Vlore"
cboCity.AddItem "Korce"
cboCity.AddItem "Gjirokaster"
cboCity.AddItem "Sarande"
cboCity.AddItem "Fier"
cboCity.AddItem "Lushnje"
cboCity.AddItem "Lezhe"
cboCity.AddItem "Diber"
cboCity.AddItem "Kukes"
cboCity.AddItem "Kavaje"
cboCity.AddItem "Permet"
Activity = "mesatar
End Sub
Programim object-oriented Faqa 144
Ngjarja optLevel Click:
Private Sub optLevel_Click(Index As Integer)
‘Percakton nivelin
Select Case Index
Case 0
Activity = "ekstrem
Case 1
Activity = "te avancuar”
Case 2
Activity = "mesatar”
Case 3
Activity = "fillestar”
End Select
End Sub
Ngjarja txtAge KeyPress:
Private Sub txtAge_KeyPress(KeyAscii As Integer)
'Lejon vetem numra ne fushen mosha
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyBack Then
Exit Sub
Else
KeyAscii = 0
End If
End Sub
Programim object-oriented Faqa 145
5. Gjuha Visual Basic 6.0. Eksplorimi i kontrolleve të Toolbox –it të Visual Basic (vazhdim)
Eksplorimi i kontrolleve të Toolbox –it të Visual
Basic
Në këtë kapitull do të vazhdoje shqyrtimi i kontrolleve të tjera të shiritit të
kontrolleve (toolbox) të Visual Basic. Do të shqyrtohen kontrollet e vizatimit,
ashensorët dhe kontrollet që mundësojnë bashkëveprimin me driver-at,
direktoritë dhe skedarët. Gjatë zhvillimit të shembujve, përpiquni që të
ndërtoni ndërfaqet dhe kodin e programimit duke ju referuar sa më pak që të
jetë e mundur materialit. Kjo do t’ju ndihmojë në rritjen e aftësive tuaja
programuese.
Programim object-oriented Faqa 146
Shtesat përbërëse të një forms-i (Display Layers)
Në këtë kapitull së pari do të njiheni me kontrollet grafike: line, shape,
picture box, dhe image box. Së pari është e nevojshme të flitet për
shtresat përbërëse të një forms-i.
Elementët që vendosen dhe paraqiten në një form, nuk vendosen të gjithë
në të njëjtën shtresë të afishimit. Forms-i përbehet nga tre shtresa të tilla.
Informacioni i paraqitur direkt në form (me ndihmën e komandës print,
ose me ndihmën e metodave grafike) shfaqet në shtresën e poshtëme
(bottom-layer). Informacioni i kontrolleve label, image box, line dhe
shape, shfaqet në shtresën e mesme (middle-layer). Të gjithë kontrollet
e tjera shfaqen në shtesën e sipërme (top-layer).
Kjo do të thotë se duhet të jeni të kujdesshëm gjatë vendosjes së
objekteve në form, pasi disa prej tyre mund të mbivendosin të tjerë. P.sh.
një tekst i afishuar në një form nuk do të arrijë të shfaqet nëse një buton
Programim object-oriented Faqa 147
Bottom-layer: form
Middle-layer: label, image, shape, line
Top-layer: të gjithë kontrollet dhe objektet e tjera
vendoset në krye të formës (në vendin ku normalisht do të afishohej
teksi). Objektet e vizatuar me kontrollet line dhe shape mbulohen nga të
gjithë kontrollet e tjera me përjashtim të kontrollit image box.
Një pyetje tjetër që mund të bëhet në këtë rast është: si përcaktohet
pozicioni relativ i objekteve në të njëjtën shtresë. P.sh. nëse kemi dy
butona në të njëjtën zonë të formës, cili do të qëndrojë në krye? Rendi
sipas së cilit vendosen kontrollet në të njëjtën shtresë quhet Z-order. Ky
rend vendoset automatikisht gjatë ndërtimit të formës. Elementët e
vendosur së fundi mbi elementët e vendosur më parë “i mbulojnë” këta të
fundit. Megjithatë renditja e paracaktuar gjatë ndërtimit të aplikimit mund
të ndryshojë. Për këtë për të sjellë në plan të parë një objekt të mbuluar
nga një tjetër duhet klikuar objekt dhe më pas të zgjidhet komanda Bring
to Front e menusë Format/Order e editorit të Visual Basic. Komanda
Send to Back ka efektin e kundërt. Theksojmë që këto dy komanda kanë
efekt ndërmjet kontrolleve të së njëjtës shtresë, pra nuk mund të
aplikohen ndërmjet një vije të vizatuar me ndihmën e kotrollit line (që
ndodhet në shtresën e mesme) dhe një butoni (që ndodhet në shtresën e
sipërme).
Programim object-oriented Faqa 148
Kontrolli Line
Kontrolli line shërben për të krijuar segmente vijash të drejta, të ngjyrave
dhe trashësive të ndryshme. Bashkë me kontrollin shape për të cilin do të
flitet më pas, ju mund ta përdorni këtë kontroll për të ‘zbukuruar’ aplikimin
tuaj.
Disa nga vetitë e kontrollit Line:
BorderColor Përcakton ngjyrën e vijës.
BorderStyle Përcakton llojin e vijës. Ajo mund të jetë
transparente, e vazhduar, e ndërprerë, me pika,
dhe e kombinuar.
BorderWidth Përcakton trashësinë e vijës.
Kontrolli Line nuk ka as metoda dhe as ngjarje.
Përderisa kontrolli line i takon shtresës së mesit, vijat e vendosura në form
do të mbulohen nga çdo kontroll i vendosur mbi to, përveç kontrollit image
box, dhe kontrollit shape.
Programim object-oriented Faqa 149
Kontrolli Shape
Kontrolli shape shërben për vizatimin e rrathëve, elipseve, katrorëve,
drejtëkëndshave (me kulme të drejta ose të rrumbullakosura). Ngjyra të
ndryshme mund të përdoren në konturet dhe pjesën e brendëshme të këtyre
figurave gjeometrike.
Vetitë e kontrollit Shape:
BackColor Përcakton ngjyrën e sfondit te objektit shape
(përdoret vetëm kur vetia FillStyle nuk ka vlerën
Solid).
BackStyle Përcakton nëse sfondi është apo jo transparent.
BorderColor Përcakton ngjyrën e konturit.
BorderStyle Përcakton stilin e konturit. Ai mund të jetë
transparent, i vazhduar, me vija, me pika dhe i
kombinuar.
BorderWidth Përcakton trashësinë e konturit.
FillColor Përcakton ngjyrën e brendëshme të objektit
shape.
FillStyle Përcakton modelin brendshëm të objektit shape.
Disa nga mundësitë janë: solid, transparent, me
viza kryq, etc.
Programim object-oriented Faqa 150
Shape Përcakton nëse shape do të jetë katror,
drejtëkëndësh, rreth, elips, etj.
Ashtu sikurse dhe kontrolli line, kontrolli shape nuk përmban as ngjarje as
metoda.
Objektet shape “mbulohen” nga të gjithe objektet e tjera të vendosur në
forms, me përjashtim të kontrollit line dhe image box.
Programim object-oriented Faqa 151
Scroll bar (Ashensorët Horizontalë dhe Vertikalë)
Ashensorët horizontalë dhe vertikalë kanë një përdorim shumë të gjerë në
aplikimet e Windows-it. Ato ofrojnë një mundësi për të lëvizur në një listë
informacioni dhe shërbjenë gjithashtu dhe si kontrolle për leximin e
informacionit dhe futjen e tij në program (input device).
Të dy tipet e ashensorëve përbëhen nga tre zona në të cilat mund të klikohet
ose të rrëshkitet. Këto janë:
Duke klikuar në Shigjetën e fundit rritet vlera e kutisë rrëshkitëse me
një njësi të vogël, duke klikuar në zonën rrëshkitëse rritet vlera e kutisë
rrëshkitëse me një njësi të madhe. Tërheqja e kutisë rrëshkitëse e ndryshon
vlerën në varësi të pozicionit ku lëshohet. Duke përdorur vetitë e kontrollit
mund të përcaktohet krejtësisht mënyra se si do të punojë ai. Pozicioni i
kutisë rrëshkitëse është i vetmi informacion dalës që ofron kontrolli Scroll
bar.
Programim object-oriented Faqa 152
Shigjeta fundit
Kutia rrëshkitëse Zona rrëshkitëse
Vetitë kryesore të kontrollit Scroll Bar:
LargeChangeVlera e cila i shtohet ose i hiqet vetisë Value të
scroll bar-it, kur klikohet zona rrëshkitëse.
Max Vlera e një scroll bar-i horizontal në skajin e
djathtë të tij, dhe e një scroll bari veritkal në
skajin e poshtëm të tij. Kufijtë e kësaj vlere janë -
32,768 deri në 32,767.
Min Vlera e ekstremit tjetër, e skajit të majtë në scroll
bar-in horizantal, dhe e skajit të sipërm në scroll
bar-in vertikal. Kufijtë e kësaj vlere janë -32,768
deri në 32,767.
SmallChangeVlera që i shtohet ose i zbritet vetisë Value, kur
klikohet në njërën nga dy shigjetat e scroll bar-it.
Value Pozicioni aktual i kutisë rrëshkitëse të scroll bar-
it. Nëse kjo vlerë përcaktohet me kod, atëherë
Visual Basic e lëviz kutinë rrëshkitëse në
pozicionin e duhur.
Vetitë pë scroll bar-in horizontal:
Programim object-oriented Faqa 153
Min
SmallChange
SmallChangeLargeChange
LargeChangeValue
Max
Vetitë për scroll barin vertikal:
Disa shënime të rëndëishme për kontrollin scroll bar:
1. Vini re se megjithëse vlerat e ekstremeve quhen Min dhe Max, ato
nuk paraqesin domosdoshmërisht minimumin dhe maksimumin e
vlerave. Pra vlera Min mund të jetë më e madhe se vlera Max. Në
rastin e scroll bar-eve vertikalë kjo është diçka e zakonshme. Visual
Basic e rregullon në mënyrë automatike shenjën e vetive
SmallChange dhe LargeChange për të siguruar lëvizjen e kutisë
rrëshkitëse nga njëri ekstrem tek tjetri.
2. Nëse ndryshoni në kod vlerat e vetive Value, Min, ose Max,
sigurohuni që vlera e vetisë Value të jetë gjithnjë ndërmjet vlerave të
vetive Min dhe Max, në të kundërt programi do të ndalojë duke
afishuar një mesazh gabimi.
Programim object-oriented Faqa 154
SmallChange
SmallChange
LargeChange
LargeChange
Value
Max
Min
Programim object-oriented Faqa 155
Ngjarjet kryesore të kontrollit Scroll Bar:
Change Ndodh kur ndryshon pozicioni i kutisë rrëshkitëse.
Kjo ngjarje përdoret për të marrë vlerën e vetisë
Value pas çdo ndryshimi në scroll bar.
Scroll Ndodh gjatë lëvizjes së kutisë rrëshkitëse.
Programim object-oriented Faqa 156
Shembull 5-1
Konvertuesi i temperaturave
Hapni një projekt të ri. Qëllimi i programit është të konvertojë temperaturat
nga sistemi Fahrenheit në atë Celsius. Siç e theksuam në fillim të kapitullit,
ju do të përpiqeni ta ndërtoni aplikimin duke ju referuar në minimun zgjidhjes
së mëposhtëme.
Specifikimet e aplikimit “Konvertuesi i temperaturave”
Ky aplikim duhet të ketë një scroll bar i cili modifikon vlerën e
temperaturës në sistemin Fahrenheit (nga një minimum deri në
një maksimum të arsyeshëm). Kur përdoruesi ndryshon vlerën e
scroll bar-it, në form duhet të afishohen temperaturat në
Fahrenheit dhe në Celsius (vlerën e këtij të fundit duhet ta
llogarisni bazuar në formulën e mëposhtëme). Formula për
konvertimin nga Fahrenheit (F) në Celsius (C) është:
C = (F - 32)*5/9
Për të rrumbullakuar një numër në numër të plotë përdorni
funksionin CInt() të Visual Basic. Për të konvertuar një numër në
një string që afishohet në një label ose text box, përdorni
funksionet Str() ose Format(). Përpiquni ta ndërtoni aplikimin pa
parë zgjidhjen e tij. Shtoni në aplikim dhe elemente zbukurimi
me ndihmën e kotrolleve line dhe shape.
Programim object-oriented Faqa 157
Një metodë e mundëshme zgjidhje e aplikimit “Konvertuesi i
temperaturave”:
1. Vendosni një shape, një scroll bar vertikal, katër label, dhe një command
button në form. Vendosni kontrollin scroll bar brenda shape-it.
2. Vetitë e formës dhe të çdo kontrolli:
Form1:
BorderStyle 1-Fixed Single
Caption Konvertuesi i temperaturave
Name frmTemp
Shape1:
BackColor White
Programim object-oriented Faqa 158
Shape1
BackStyle 1-Opaque
FillColor Red
FillStyle 7-Diagonal Cross
Shape 4-Rounded Rectangle
VScroll1:
LargeChange 10
Max -60
Min 120
Name vsbTemp
SmallChange 1
Value 32
Label1:
Alignment 2-Center
Caption Fahrenheit
FontSize 10
FontStyle Bold
Label2:
Alignment 2-Center
AutoSize True
BackColor White
BorderStyle 1-Fixed Single
Programim object-oriented Faqa 159
Caption 32
FontSize 14
FontStyle Bold
Name lblTempF
Label3:
Alignment 2-Center
Caption Celsius
FontSize 10
FontStyle Bold
Label4:
Alignment 2-Center
AutoSize True
BackColor White
BorderStyle 1-Fixed Single
Caption 0
FontSize 14
FontStyle Bold
Name lblTempC
Command1:
Cancel True
Caption &Dalje
Programim object-oriented Faqa 160
Name cmdExit
Vini re që temperatura fillestare është përcaktuar 32F dhe 0C.
Tashmë forma do të ketë këtë pamje:
3. Kodi në seksionin General declarations.
Option Explicit
Dim TempF As Integer
Dim TempC As Integer
Krijon dy variabla globalë për temperaturat në secilën shkallë.
4. Kodi në ngjarjen Scroll të kontrollit scroll bar.
Programim object-oriented Faqa 161
Private Sub vsbTemp_Scroll()
'Lexon F dhe e konverton ne C
TempF = vsbTemp.Value
lblTempF.Caption = Str(TempF)
TempC = CInt((TempF - 32) * 5 / 9)
lblTempC.Caption = Str(TempC)
End Sub
Kjo pjesë kodi përcakton vlerën e vetisë Value të scroll bar-it pas ndryshimit
të tij, e vendos vlerën e tij në variablin e temperaturës në shkallën
Fahrenheit, llogarit vlerën korresponduese në shkallën Celsius, dhe afishon
të dy vlerat.
5. Kodi në ngjarjen Change të scroll bar-it.
Private Sub vsbTemp_Change()
'Lexon F dhe e konverton në C
TempF = vsbTemp.Value
lblTempF.Caption = Str(TempF)
TempC = CInt((TempF - 32) * 5 / 9)
lblTempC.Caption = Str(TempC)
End Sub
Vini re se ky kod është identik me atë të ngjarjes Scroll. Një dublikim i tillë
kodi në këto dy ngjarje, bëhet gjithnjë gjatë përdorimit të kotrollit scroll bar.
Programim object-oriented Faqa 162
6. Ngjarja në procedurën cmdExit_Click.
Private Sub cmdExit_Click()
End
End Sub
7. Testoni programin. Sigurohuni që informacioni i paraqitur prej tij është i
saktë. P.sh. 32F gjithnjë duhet të japë 0C! Regjistroni projektin. Do t’i
kthehemi përsëri atij në kapitullin 5.
Kërkesë:
A mund të gjeni pikën kur temperatura Fahrenheit është
e barabartë me temperaturën Celsius?
Programim object-oriented Faqa 163
Kontrolli Picture Box
Kontrolli picture box ju lejon të vendosni informacione grafike në forms-in
tuaj. Ka një përdorim të gjerë në paraqitjet dinamike si p.sh. animimet
Picture box vendoset në shtresën e sipërme të forms-it. Ato sillen në mënyrë
të ngjashme me një forms të vogël brenda një forms-i, meqënëse kanë
shumë veti të përbashkëta me një form.
Vetitë kryesore të kontrollit Picture Box:
AutoSize Nëse është True, picture box-i ridimensionohet
automatikisht për të paraqitur të plotë pamjen
grafike.
Font Përcakton madhësinë dhe stilin e shkrimit të çdo
teksti që mund të afishohet në picture box.
Picture Përcakton skedarin grafik, përmbajtja e së cilit do
të afishohet në picture box.
Disa nga ngjarjet e Picture Box:
Click Ndodh kur klikohet në kontrollin picture box.
DblClick Ndodh kur klikohet dy herë në kontrollin picture
box.
Programim object-oriented Faqa 164
Metodat e Picture Box:
Cls Pastron përmbajtjen e picture box-it.
Print Afishon një informacion në picture box.
Shembuj
picExample.Cls ' pastron përmbajtjen e kontrollit picExample
picExample.Print "një picture box" ' afishon një string në picture
box
Procedura LoadPicture e një Picture Box-i:
Një funksion shumë i rëndësishëm, i lidhur ngushtësisht me kontrollin
picture box është procedura LoadPicture. Ajo përdoret për të përcaktuar
vlerën e vetisë Picture të picture box-it gjatë ekzekutimit të programit.
Shembull
picExample.Picture = LoadPicture("c:\pix\sample.bmp")
Kjo komandë ngarkon skedarin grafik c:\pix\sample.bmp në vetinë Picture
të kontrollit picExample. Argumenti i funksionit LoadPicture duhet të jetë
rrugëkalimi i saktë i një skedari grafik, përndryshe programi do të
sinjalizojë një mesazh gabimi dhe do të ndalojë ekzekutimin.
Programim object-oriented Faqa 165
Pesë tipe skedarësh grafikë mund të ngarkohen në një kontroll picture box:
Bitmap Një imazh i paraqitur nga pixel dhe i ruajtur si
bashkësi bit-esh, në të cilin çdo bit i korrespondon
një pixeli. Ka prapashtesën .bmp. Shfaqet në
madhësi origjinale.
Icon Një tip special skedari bitmap me madhësi jo më
të madhe se 32 x 32. Kanë prapashtesën .ico.
Shfaqen në madhësinë origjinale.
Metafile Një skedar që ruan një imazh jo me pixel por si
koleksion objektesh grafike (vijash, rrathësh,
drejtëkëndshash). Skedarët Metafiles ofrojnë një
imazh më të saktë sesa bitmap kur ato
ridimensionohen. Kanë prapashtesën .wmf.
Ridimensionojnë vetveten kur afishohen në një
kontroll picture box.
JPEG JPEG (Joint Photographic Experts Group) është një
skedar i kompresuar bitmap që suporton ngjyra 8
dhe 24 bit. Është popullor në internet. Ka
prapashtesën .jpg dhe kompresohet kënaqshëm.
GIF GIF (Graphic Interchange Format) është një
skedar bitmap i kompresuar i zhvilluar fillimisht
nga CompuServe. Ai suporton të paktën 256
ngjyra dhe është shumë popullor në internet. Ka
prapashtesën .gif dhe kompresohet kënaqshëm.
Programim object-oriented Faqa 166
Kontrolli Image Box
Një image box është shumë i ngjashëm me një picture box, në kuptimin që
ju lejon ku të afishoni në të një informacion grafik. Kontrollet Image box janë
më të përshtatshme për situata statike – d.m.th. në raste kur informacioni
grafik që ato paraqesin nuk do të ndryshojë me kalimin e kohës.
Image box shfaqen në shtresën e mesme të forms-it, si pasojë ato mbulohen
nëse kontrolle të tjera (përfshi këtu dhe picture boxes) vendosen mbi to.
Figura e shfaqur në një kotroll image box mund të ridimensionohet duke
përdorur vetinë Stretch.
Disa nga vetitë e Image Box:
Picture Përcakton skedarin grafik që do të afishohet në
image box.
Stretch Nëse është False, image box ridimensionohet për
të paraqitur të plotë figurën. Nëse është True,
figura ridimensionohet për t’ju përshtatur
përmasave të kontrollit.
Ngjarjet e Image Box:
Click Ndodh kur klikohet në image box.
DblClick Ndodh kur klikohet dy herë në image box.
Programim object-oriented Faqa 167
Image box-i nuk përmban asnjë metodë, megjithatë ai përdor ekzaktësisht si
dhe picture box-i, funksionin LoadPicture. Ashtu si dhe picture box-i, image
box-i mund të ngarkojë të njëjtët tipa skedarësh grafikë:bitmap (.bmp), icon
(.ico), metafiles (.wmf), GIF files (.gif), dhe JPEG files (.jpg).
Shembull: Picture box dhe Image box
1. Hapni një projekt të ri. Vendosni në form një picture box dhe një image
box.
2. Vendosni në vetinë Picture të secilit kontroll të njëjtin skedar grafik.
3. Vini re çfarë ndodh kur ju ridimensiononi dy kontrollet. Vini re efektin e
shtresave kur i vendosni kontrollet njëri mbi tjetrin. Vini re efektin e vetisë
Stretch të image box-it, të aplikuar në tipe të ndryshëm skedarësh
grafikë - çfarë diference vini re?
Programim object-oriented Faqa 168
Kontrolli Drive List Box
Kontrolli drive list box lejon përdoruesin të zgjedhë në momentin e
ekzekutimit të programit një driver të vlefshëm të kompjuterit. Lista e këtyre
driver-ave shfaqet në një combo box. Visual Basic e ngarkon listen e driver-
ave pa qenë nevoja e shkrimit të kodit shtesë nga programisti.
Vetitë më të rëndësishme të kontrollit Drive List box:
Drive Përmban emrin e driver-it të zgjedhur.
Ngjarja kryesore e kontrollit Drive List Box:
Change Ndodh kur përdoruesi ndryshon driver-in e
zgjedhur.
Programim object-oriented Faqa 169
Kontrolli Directory List Box
Kontrolli directory list box afishon në mënyrë të renditur dhe hierarkike
listen e direktorive dhe nëndirektorive të driver-it të zgjedhur. Struktura
hierarkike e direktorive afishohet automatikisht në kontrollin list box., ashtu
si dhe në rastin e kontrollit Driver list box, pa qenë nevoja e shkrimit të kodit
shtesë.
Vetia kryesore e kontrollit Directory List Box:
Path Rrugëkalimi aktual.
Ngjarja kryesore e kontrollit Directory List Box:
Change Ndodh kur ndryshon direktoria e zgjedhur.
Programim object-oriented Faqa 170
Kontrolli File List Box
Kontrolli file list box lokalizon dhe liston skedarët në direktorinë e
përcaktuar në vetinë Path. Mundet të përcaktohet dhe tipi I skedarëve që
dëshironi të listoni.
Vetitë kryesore të kontrollit File List Box:
FileName Përmban ekrin e skedarit të zgjedhur.
Path Përmban rrugëkalimin aktual.
Pattern Përmban një string që përcakton tipet e
skedarëve që do të afishohen. Suporton
përdorimin e karaktereve * dhe ?. Për shembull,
*.dat do të afishojë vetëm skedarët me
prapashtesën dat.
Ngjarjet e kontrollit File List Box:
DblClick Ndodh kur klikohet dy here tek skedari i zgjedhur.
PathChange Ndodh kur ndryshon rrugëkalimi i skedarit të
zgjedhur në kontrollin file list box.
Programim object-oriented Faqa 171
Ju mund të përdorni vetinë MultiSelect të kontrollit file list për të lejuar
selektimin e disa skedarëve njëherësh.
Programim object-oriented Faqa 172
Sinkronizimi i kontrolleve Drive, Directory, dhe File List Boxes
Kontrollet drive, directory, dhe file list box në përgjithësi përdoren së bashku
për të përftuar emrin e një skedari. Në këtë mënyrë është e rëndësishme që
veprimet e tyre të sinkronizohen për të siguruar konsistencë të informacionit
të afishuar. Kur ndryshon driver-i i zgjdhur (ngjarja Change e drive box),
duhet të bëhet rifreskimi i direktorive. P.sh. nëse drive box është emërtuar
drvExample dhe directory box është dirExample, kodi do të ishte:
dirExample.Path = drvExample.Drive
Kur ndryshon direktoria e zgjdhur (ngjarja Change e directory box), duhet të
rifreskoni listën e skedarëve. Kur file box emërtohet filExample, kodi do të
ishte:
filExample.Path = dirExample.Path
Kur janë bërë të gjitha zgjedhjet, dhe ju doni të përftoni emrin e skedarit të
zgjedhur, ju duhe të formoni një string që specifikon në mënyrë të plotë dhe
korrekte skedarin e identifikuar. Ky string duhet të bashkojë informacionet e
driver-it, direktorisë dhe emrin e skedarit. Kjo është një punë e lehtë me
përjashtim të një rasti kur ka një problem të vogël. Problemi ka lidhje me
karakterin backslash (\). Nëse ju jeni të pozicionuar në direktorinë rrënjë të
driver-it të zgjedhur, rrugëkalimi përfundon me backslash. Në të kundërt, pra
nuk jeni në rrënjë, rrugëkalimi nuk mbaron me backslash, si rrjedhojë në
këtë rast ju duhet ta shtoni atë, përpara shtimit të emrit të skedarit.
Programim object-oriented Faqa 173
Shembull i kodit të bashkimit të informacionit dhe ngarkimit të imazhit:
Dim YourFile as String
If Right(filExample.Path,1) = "\" Then
YourFile = filExample.Path + filExample.FileName
Else
YourFile = filExample.Path + "\" + filExample.FileName
End If
imgExample.Picture = LoadPicture(YourFile)
Programim object-oriented Faqa 174
Ushtrim 5-2
Afishimi i imazheve
Hapni një projekt të ri. Në këtë aplikim do të kërkohen skedarët grafikë në
skedarët e kompjuterit dhe do të afishohet pamja e tyre në një image box.
Specifikimet e aplikimit
Zhvilloni një aplikim ku përdoruesi të kërkojë dhe të gjejë
skedarët grafikë (*.ico, *.bmp, *.wmf) në kompjuterin e tij. Kur
zgjidhet një skedar i tillë, emri dhe rrugëkalimi i tij të afishohet
në një label dhe imazhi i tij të shfaqet në një image box me
ndihmën e funksionit LoadPicture().
Programim object-oriented Faqa 175
Nje mundesi zgjidhje per Image Viewer:
1. Vendosni një drive list box, directory list box, file list box, katër label, një
line dhe një buton në form. Shtoni gjithashtu një image box dhe
vendoseni atë që të duket si në figurën e mëposhtëme brenda dy
kontrolleve Shape. Forma duhet të ketë pamjen e mëposhtëme:
2. Vendosni vetitë e formës dhe çdo objekti si më poshtë:
Form1:
BorderStyle 1-Fixed Single
Caption Paraqitja e imazheve
Name frmImage
Drive1:
Name drvImage
Dir1:
Programim object-oriented Faqa 176
Line1
Image1
Shape1
Shape2
Name dirImage
File1:
Name filImage
Pattern *.bmp;*.ico;*.wmf;*gif;*jpg
[ky rresht shtypet pa hapsira]
Label1:
Caption [Bosh]
BackColor Yellow
BorderStyle 1-Fixed Single
Name lblImage
Label2:
Caption Skedarët:
Label3:
Caption Direktoritë:
Label4:
Caption Driver-at:
Command1:
Caption &Shfaq imazhin
Default True
Name cmdShow
Command2:
Programim object-oriented Faqa 177
Cancel True
Caption &Dalje
Name cmdExit
Line1:
BorderWidth 3
Shape1:
BackColor Cyan
BackStyle 1-Opaque
FillColor Blue
FillStyle 4-Upward Diagonal
Shape 4-Rounded Rectangle
Shape2:
BackColor White
BackStyle 1-Opaque
Image1:
BorderStyle 1-Fixed Single
Name imgImage
Stretch True
3. Kodi në ngjarjen drvImage_Change.
Private Sub drvImage_Change()
'N.q.s ndryshon driver-i, freskon direktoritë
dirImage.Path = drvImage.Drive
Programim object-oriented Faqa 178
End Sub
Kur zgjidhet një driver i ri, ky kod detyron listën e direktorive të rifreskohet
me listën e direktorive të driver-it të zgjedhur.
4. Kodi në ngjarjen dirImage_Change.
Private Sub dirImage_Change()
'N.q.s. ndryshon direktoria, freskon skedarët
filImage.Path = dirImage.Path
End Sub
Njësoj, kur zgjidhet një direktori e re, duhet të shikojmë skedarët e kësaj
direktorie.
5. Kodi në ngjarjen cmdShow_Click.
Private Sub cmdShow_Click()
'Bashkon emrin e skedarit me rrugëkalimin e tij dhe
'ngarkon imazhin ne kontrollin image box
Dim ImageName As String
'kontrollon nese kemi te bejme me direktorine rrenje
If Right(filImage.Path, 1) = "\" Then
ImageName = filImage.Path + filImage.filename
Else
ImageName = filImage.Path + "\" + filImage.filename
End If
lblImage.Caption = ImageName
imgImage.Picture = LoadPicture(ImageName)
End Sub
Ky kod formon emrin e skedarit duke bashkuar rrugekalimin e direktorise me
emrin e skedarit. Më pas me ndihmën e funksionit LoadPicture imazhi i
zgjedhur afishohet në image box.
Programim object-oriented Faqa 179
6. Kopjoni kodin e shkruar në ngjarjen cmdShow_Click dhe vendoseni atë
në ngjarjen filImage_DblClick. Ky kod është identik meqë duam të kemi
të njëjtin rezultat edhe kur klikojmë dy herë në emrin e skedarit që duam
të shfaqim. (Kur të mësoni në kapitullin tjetër se si mund të thirret një
procedurë nga një tjetër do të vini re se ky dyfishim kodi është i
panevojshëm).
7. Kodi në ngjarjen cmdExit_Click.
Private Sub cmdExit_Click()
End
End Sub
8. Regjistrojeni projektin. Ekzekutojeni atë, gjeni skedarët bitmaps, icons,
dhe metafiles. Vini re se si vetia Stretch e image box ndikon në paraqitjen
e figurave:
Kontrolli Common Dialog Box
Programim object-oriented Faqa 180
Qëllimi kryesor i përdorimit të kontrolleve drive, directory, dhe file name list
box është zhvillimi i procedurave të manipulimit të skedarëve. Dy nga
procedurat më të zakonshme në aplikimet e bazur në Windows janë
procedurat Open File dhe Save File. Fatmirësisht këto procedura në Visual
Basic ofrohen të gatshme.
Për ti dhënë përdoruesit një ndërfaqe standarte në të gjithë aplikimet e
ndërtuar në Windowsm Visual Basic ka vënë në shërbim të programistëve
kontrollin common dialog box, dy nga funksionet e të cilit janë dritaret
Open dhe Save As. Këto dritare janë familjare për çdo përdorues të
Windows-it dhe i japin aplikimit tuaj një pamje profesionale.
N.q.s kontrolli common dialog box nuk shfaqet në dritaren e kontrolleve të
Visual Basic, ju duhet ta shtoni atë. Kjo gjë bëhet duke zgjedhur komandën
Components në menunë Project. Në dritaren e afishuar zgjidhni në listën e
kontrolleve Microsoft Common Dialog Control, dhe më pas klikoni në
butonin OK.
Kontrolli common dialog box, megjithëse në momentin e ndërtimit të
aplikimit shfaqet në forms, ai është i padukshëm gjatë ekzekutimit të
programit. Ky kontroll aktivizohet gjatë ekzekutimit të programit, me
ndihmën e njërës nga pesë metodat ‘Show’:
Programim object-oriented Faqa 181
Method Common Dialog Box
ShowOpen Open dialog box
ShowSave Save As dialog box
ShowColor Color dialog box
ShowFont Font dialog box
ShowPrinter Printer dialog box
Formati i afishimit të dritares së dialogut Open me ndihmën e kontrollit
cdlExample është:
cdlExample.ShowOpen
Kontrolli kthehet në program në rreshtin pasardhës, menjëherë pas mbylljes
së dritares Open. Dritaret e shfaqura me ndihmën e kontrollit Common
dialog box janë system modale.
Mësimi i përdorimit të të gjitha funksionaliteteve të kontrollit common dialog
box do ië kërkonte një kohë të gjatë, kështu që ne do të ndalemi më
hollësisht tek dritaret Open dhe Save As.
Programim object-oriented Faqa 182
Dritarja Open e kontrollit Common Dialog Box
Dritarja Open e kontrollit common dialog box i ofron përdoruesit mekanizmin
për specifikimin e emrit të skedarit që do të hapet. Me mënyrën e hapjes së
tij ju do të njiheni në kapitullin 6. Dritarja Open afishohet me ndihmën e
metodës ShowOpen. Në figurën e mëposhtëme paraqitet një shembull i
dritares Open:
Vetitë e dritares së dialogut Open:
CancelError N.q.s është True, gjenerohet një gabim në
momentin kur përdoruesi shtyp butonin Cancel. Ju
lejon të përdorni procedurat e trajtimit të
Programim object-oriented Faqa 183
gabimeve për të konstatuar klikimin në butonin
Cancel.
DialogTitle Stringu që afishohet në shiritin e titullit të dritares
Open. Nëse nuk përcaktohet një string i tille
shfaqet automatikisht ‘Open’.
FileName Përcakton vlerën fillestare që shfaqet më fushën
File name. Pasi dritarja mbyllet, kjo veti përdoret
për të lexuar emrin e skedarit që është zgjedhur
për tu hapur.
Filter Përdoret për të kufizuar listën e skedarëve që do
të shfaqen në file list box. Specifikimet e plota për
formatimin e Filtrit mund të gjenden në helpin e
Visual Basic. Në shembullin e paraqitur në figurë
Filtri është përdorur për të filtruar skedarët që
mund të happen me ndihmën e Microsoft Word-it:
Word (*.doc)|*.doc| Document Template (*.dot)|
*.dot| Internet files (*.html)|*.html|, Internet
files(*.htm)|*.htm| Rich Text Format (*.rtf)|*.rtf.
FilterIndex Përcakton ciIi komponent i filtrimit do të jetë aktiv
në momentin e hapjes së dritares.
Flags Vlerë që kontrollon veçori specifike të dritares
Open (shih Appendix II).
Kur përdoruesi mbyll dritaren Open, ju duhet të kontrolloni skedarin e
zgjedhur për t’ u siguruar që ai plotëson specifikimet që kërkon aplikimi,
përpara se të përpiqeni t’a hapni atë.
Programim object-oriented Faqa 184
Shembull: Open Dialog Box
1. Hapni një projekt të ri. Vendosni në form një common dialog control, një
label, dhe një buton. Përcaktoni vetitë e mëposhtëme:
Form1:
Caption Shembull Common Dialog
Name frmCommon
CommonDialog1:
DialogTitle Dritarja Open
Filter Bitmaps (*.bmp)|*.bmp|
Icons (*.ico)|*.ico|Metafiles (*.wmf)|*.wmf
GIF (*.gif)|*.gif|JPEG (*,jpg)|*.jpg
(të gjithë në një rresht)
Name cdlExample
Label1:
BorderStyle 1-Fixed Single
Caption [Bosh]
Name lblExample
Command1:
Caption &Hap
Name cmdDisplay
Programim object-oriented Faqa 185
Pas vendosjes së kontrolleve dhe caktimit të vetive, formsi duhet të ketë
këtë pamje (gjeresine e kontrollit label caktojeni sa më të madhe):
2. Shkruani kodin e mëposhtëm në ngjarjen cmdDisplay_Click.
Private Sub cmdDisplay_Click()
cdlExample.ShowOpen
lblExample.Caption = cdlExample.filename
End Sub
Ky kod shkakton afishimin e dritares Open në momentin e klikimit të
butonit Hap, dhe vendos në label-in lblExample emrin e skedarit të
zgjedhur në momentin e mbylljes së dritares.
3. Ruajeni aplikimin. Ekzekutojeni dhe një herë provoni të zgjidhni emrin e
një skedari dhe një herë tjetër ta shkruani atë. Në këtë shembull, klikimi i
butonit Cancel nku është trajtuar, kështu që ai ka të njëjtin efekt me
klikimin e butonit OK.
4. Vini re se në rast se ju zgjidhni një skedar, herën tjetër kur e hapni përsëri
dritaren Open, emri i skedarit të zgjedhur do të shfaqet në dritaren File
Name, për sa kohë që ju nuk specifikoni në kod një vlerë për vetinë
FileName.
Programim object-oriented Faqa 186
Dritarja Save As e kontrollit Common Dialog Box
Dritarja Save As e kontrollit common dialog box i ofron përdoruesit
mekanizmin e specifikimit të emrit të skedarit që do të regjistrohet. Mënyrën
e regjistrimit do ta shikoni hollësisht në kapitullin 6. Dritarja afishohet me
ndihmën e metodës ShowSave. Figura e mëposhtëme paraqet një shembull
të përdorimit të dritares Save As:
Vetitë kryesore të dritares Save As (shumica të ngjashme me ato të dritares
Open):
CancelError N.q.s është True, gjenerohet një gabim në
momentin kur përdoruesi shtyp butonin Cancel. Ju
lejon të përdorni procedurat e trajtimit të
Programim object-oriented Faqa 187
gabimeve për të konstatuar klikimin në butonin
Cancel.
DefaultExt Përcakton prapashtesën e skedarit nëse skedari
është listuar pa një prapashtesë.
DialogTitle Stringu që afishohet në shiritin e titullit të dritares
Save As. Nëse nuk përcaktohet një string i tille
shfaqet automatikisht ‘Save As’.
FileName Përcakton vlerën fillestare që shfaqet më fushën
File name. Pasi dritarja mbyllet, kjo veti përdoret
për të lexuar emrin e skedarit që është zgjedhur
për tu hapur.
Filter Përdoret për të kufizuar listën e skedarëve që do
të shfaqen në file list box.
FilterIndex Përcakton ciIi komponent i filtrimit do të jetë aktiv
në momentin e hapjes së dritares.
Flags Vlerë që kontrollon veçori specifike të dritares Open
(shih Appendix II).
Dritarja Save File zakonisht konfigurohet në dy mënyra. Nëse një skedar po
regjistrohet për herë të parë, kemi konfigurimin Save As, me një vlerë
fillestare në vetinë FileName. Në konfigurimin Save, supozohet se skedari
është hapur më parë me një emër, kështu që në momentin e regjistrimit të
tij në vetinë FileName do të figurojë në momentin fillestar po ai emër.
Kur përdoruesi mbyll dritaren Save As, ju duhet të kontrolloni emrin e
skedarit për t’ u siguruar që ai plotëson specifikimet që kërkon aplikimi,
përpara se të përpiqeni t’a regjistroni atë. Veçanërisht të kujdesshëm duhet
Programim object-oriented Faqa 188
të tregoheni me prapashtesën e tij, në mënyrë që të pranoni vetëm ato
prapashtesa të lejuara nga aplikimi juaj.
Shembull: Dritarja Save As
1. Do të bëni vetmë një ndryshim të vogël në shembullin e mëparshëm
Open. Ndryshoni vetinë DialogTitle të kontrollit common dialog control
në: “Shembull Save As” dhe vendosni vetinë DefaultExt = “bmp”.
2. Në ngjarjen cmdDisplay_Click, ndryshoni metodën në ShowSave (hap
dritaren Save As).
3. Ruani aplikimin dhe ekzekutojeni atë. Provoni të shkruani emrin e skedarit
pa prapashtesë dhe vini re se si i shtohet nga aplikimi prapashtesa .bmp.
Vini re se përsëri butoni Cancel nuk është trajtuar kështu që ai ka të
njëjtin efekt si butoni OK.
Programim object-oriented Faqa 189
Shembull 5
Dritarja e hedhjes së të dhënave të Studentit
Ndërtoni një forms ku përdoruesi të ketë mundësi të përcaktojë këto të
dhëna për një student:
1. Emri i studentit
2. Viti (1 në 6)
3. Gjinia e studentit (Mashkullore, Femerore)
4. Data e lindjes së studentit (Muaj, Ditë, Vit)
5. Foto e studentit (Supozojmë se do të jetë një skedar .bmp)
Ndërtoni dritaren në mënyrë të tillë që vetëm emri të ketë mundësi të
shkruhet, të gjithë të dhënat e tjera të mund të zgjidhen me ndihmën e
butonave opsionale, scroll bar-eve dhe common dialog box-eve. Kur
informacioni plotësohet atëherë të afishohet një dritare mesazhi me profilin e
studentit:
Mosha e studentit duhet të llogaritet bazuar në datëlindjen e tij. Foto e
studentit do të shfaqet vetëm në dritaren e të dhënave.
Programim object-oriented Faqa 190
Zgjidhja:
Form:
Vetitë:
Form frmStudent:
BorderStyle = 1- Fixed Single
Caption = Profili i studentit
CommandButton cmdLoad:
Caption = &Ngarko foton
Frame Frame3:
Caption = Foto
FontName = MS Sans Serif
Programim object-oriented Faqa 191
txtName
Label1
optLevel
Frame4
Frame2
optSex
lblMonth
lblDay
lblYearFrame1
Frame3
imgStudent
cmdLoad
vsbMonth
vsbDay
vsbYear
cmdShow
cmdNew
cmdExit
cdlBox
FontBold = True
FontSize = 9.75
FontItalic = True
Image imgStudent:
BorderStyle = 1 - Fixed Single
Stretch = True
CommandButton cmdExit:
Caption = &Dalje
CommandButton cmdNew:
Caption = &Profil i ri
CommandButton cmdShow:
Caption = &Afisho Profilin
Frame Frame4:
Caption = Datelindja
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
OptionButton optLevel:
Caption = Viti 6
Index = 5
Programim object-oriented Faqa 192
OptionButton optLevel:
Caption = Viti 5
Index = 4
OptionButton optLevel:
Caption = Viti 4
Index = 3
OptionButton optLevel:
Caption = Viti 3
Index = 2
OptionButton optLevel:
Caption = Viti 2
Index = 1
OptionButton optLevel:
Caption = Viti 1
Index = 0
Frame Frame2:
Caption = Gjinia
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
Programim object-oriented Faqa 193
OptionButton optSex:
Caption = Femer
Index = 1
OptionButton optSex:
Caption = Mashkull
Index = 0
Frame Frame1:
Caption = Datelindja
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
VScrollBar vsbYear:
Max = 1800
Min = 2100
Value = 1960
VScrollBar vsbDay:
Max = 1
Min = 31
Value = 1
Programim object-oriented Faqa 194
VScrollBar vsbMonth:
Max = 1
Min = 12
Value = 1
Label lblYear:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 10.8
Label lblDay:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 10.8
Label lblMonth:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
Programim object-oriented Faqa 195
FontSize = 10.8
TextBox txtName:
FontName = MS Sans Serif
FontSize = 10.8
CommonDialog cdlBox:
Filter = Bitmaps (*.bmp)|*.bmp
Label Label1:
Caption = Emri
FontName = MS Sans Serif
FontBold = True
FontSize = 9.75
FontItalic = True
Kodi:
General Declarations:
Option Explicit
Dim Months(12) As String
Dim Days(12) As Integer
Dim Grade As String
Ngjarja cmdExit Click:
Private Sub cmdExit_Click()
End
Programim object-oriented Faqa 196
End Sub
Ngjarja cmdLoad Click:
Private Sub cmdLoad_Click()
cdlbox.ShowOpen
imgStudent.Picture = LoadPicture(cdlbox.filename)
End Sub
Ngjarja cmdNew Click:
Private Sub cmdNew_Click()
'boshatis fushen emri dhe imazhin
txtName.Text = ""
imgStudent.Picture = LoadPicture("")
End Sub
Ngjarja cmdShow Click:
Private Sub cmdShow_Click()
Dim Is_Leap As Integer
Dim Msg As String, Age As Integer, Pronoun As String
Dim M As Integer, D As Integer, Y As Integer
'Kontrollon nëse viti është i brishtë dhe Shkurti është muaji aktual
If vsbMonth.Value = 2 And ((vsbYear.Value Mod 4 = 0 And vsbYear.Value Mod 100 <> 0) Or vsbYear.Value Mod 400 = 0) Then
Is_Leap = 1
Else
Programim object-oriented Faqa 197
Is_Leap = 0
End If
'Kontrollon nëse data korrente nuk e kalon numrin e ditëve të muajit
If vsbDay.Value > Days(vsbMonth.Value) + Is_Leap Then
MsgBox "Muaji " + Months(vsbMonth.Value) +" ka vetëm " + Str(Days(vsbMonth.Value) + Is_Leap) + " ditë.", vbOKOnly + vbCritical, "Datelindja e gabuar"
Exit Sub
End If
'Lexon datën e lindjes dhe llogarit moshën
M = Val(Format(Now, "mm"))
D = Val(Format(Now, "dd"))
Y = Val(Format(Now, "yyyy"))
Age = Y - vsbYear
If vsbMonth.Value > M Or (vsbMonth.Value = M And vsbDay > D) Then Age = Age - 1
'Kontrollon vlefshmërinë e fushës mosha
If Age < 0 Then
MsgBox "Data e lindjes është më e vogël se data e sotme.", vbOKOnly + vbCritical, "Datëlindja e gabuar"
Exit Sub
End If
'Kontrollon plotësimin e fushës emri
If txtName.Text = "" Then
MsgBox "Ju lutem plotësoni fushën emri.", vbOKOnly + vbCritical, "Fusha emri bosh"
Exit Sub
End If
Programim object-oriented Faqa 198
'Krijon dhe afishon profilin e studentit
Msg = txtName.Text + " është në vitin " + Grade + vbCr
If optSex(0).Value = True Then Pronoun = "Ai " Else Pronoun = "Ajo "
Msg = Msg + Pronoun + " është " + Str(Age) + " vjeç." + vbCr
MsgBox Msg, vbOKOnly, "Profili i studentit"
End Sub
Ngjarja Form Load:
Private Sub Form_Load()
'Inicializon vektorët për datat
Months(1) = "Janar": Days(1) = 31
Months(2) = "Shkurt": Days(2) = 28
Months(3) = "Mars": Days(3) = 31
Months(4) = "Prill": Days(4) = 30
Months(5) = "Maj": Days(5) = 31
Months(6) = "Qershor": Days(6) = 30
Months(7) = "Korrik": Days(7) = 31
Months(8) = "Gusht": Days(8) = 31
Months(9) = "Shtator": Days(9) = 30
Months(10) = "Tetor": Days(10) = 31
Months(11) = "Nëntor": Days(11) = 30
Months(12) = "Dhjetor": Days(12) = 31
lblMonth.Caption = Months(vsbMonth.Value)
lblDay.Caption = Str(vsbDay.Value)
Programim object-oriented Faqa 199
lblYear.Caption = Str(vsbYear.Value)
Grade = "I pari"
End Sub
Ngjarja optLevel Click:
Private Sub optLevel_Click(Index As Integer)
Select Case Index
Case 0
Grade = "E parë"
Case 1
Grade = "E dytë"
Case 2
Grade = "E tretë"
Case 3
Grade = "E katërt"
Case 4
Grade = "E pestë"
Case 5
Grade = "E gjashtë"
End Select
End Sub
Ngjarja vsbDay Change:
Private Sub vsbDay_Change()
Programim object-oriented Faqa 200
lblDay.Caption = Str(vsbDay.Value)
End Sub
Ngjarja vsbMonth Change:
Private Sub vsbMonth_Change()
lblMonth.Caption = Months(vsbMonth.Value)
End Sub
Ngjarja vsbYear:
Private Sub vsbYear_Change()
lblYear.Caption = Str(vsbYear.Value)
End Sub
Programim object-oriented Faqa 201
6. Gjuha Visual Basic. Krijimi i një
aplikimi Visual BasicDeri tani jeni njohur me shumicën e kontrolleve standarte te Visual Basic,
dhe jeni njohur me veçantitë sintaksore të gjuhës. Për ekzekutimin e një
aplikimi të ndërtuar në Visual Basic, për momentin duhet të keni të instaluar
dhe vetë Visual Basic. Në këtë kapitull do të njiheni me hapat që duhen
ndjekur për të krijuar skedarin e ekzekutueshëm dhe paketën e instalimit në
mënyrë që aplikimi i krijuar të mund të ekzekutohet në çdo kompjuter (me
sistem shfrytëzimi Windows) pavarësisht faktit nëse në të është i instaluar
Visual Basic apo jo. Gjithashtu në këtë kapitull do të njiheni dhe me disa
komponentë të rinj që do t’ju ndihmojnë në ndërtimin e aplikimeve.
Programim object-oriented Faqa 202
Konsiderata për ndërtimin e ndërfaqeve
Përpara fillimit të procesit të ndërtimit të një aplikimi, ndërtimit të
ndërfaqeve përkatëse, përcaktimit të vetive dhe shkrimit të kodeve, duhen
marrë në konsideratë disa gjëra:
Konsiderata e parë ka të bëjë me përcaktimin me saktësi të proceseve
dhe funksioneve që duhet të kryej aplikimi. Cilët janë të dhënat hyrëse
dhe cilat do të jenë të dhënat dalëse? Ndërtoni një bllokskemë të gjithë
proceseve të aplikimit.
Përcaktoni të gjithë kontrollet që ju nevojiten. A janë të mjaftueshëm
kontrollet dhe funksionet e Visual Basic, apo duhet të ndërtoni dhe ju
kontrolle apo funksione të tjera?
Ndërtoni ndërfaqet e përdoruesit. Si do t’ju pëlqente të dukeshin forms-et
tuaja? Vlerësoni krahas elementëve estetike dhe lehtësinë dhe
komoditetin për përdoruesin. Ndërfaqet është mirë të jenë konsistente me
aplikimet e tjera të Windows-it.
Shkruani kodin tuaj. Kodi te jete sa me i lexueshem dhe i kuptueshem, gje
qe lehteson modifikimin e tij ne te ardhmen nga programues te tjere.
Kete pike konsiderojeni si zhvillim kodesh burim – modulesh me utilitete
jashte zhvillimit tuaj te momentit. Kjo gje do t’ju kurseje kohen tuaj te
programimit ne te ardhmen.
Bejeni kodin tuaj sa me 'user-friendly.' Perpiquni qe te parashikoni te
gjitha ngjarjet dhe problemet qe nje perdorues mund te ndeshi ne
aplikacionin tuaj.
Beni Debug te gjithe kodit tuaj para se ta shperndani ate. Nuk ka asgje
me te keqe se te keni nje telefonate nga nje perdorues per shkak te
mosfunksionimit korrekt te aplikacionit. Menyra me e mire per te gjetur
gabimet eshte te lejoni njerez te ndryshem te testojne kodin tuaj – nje
program mini “beta – testim”.
Programim object-oriented Faqa 203
Perdorimi i General Sub Procedures ne Aplikacion
Deri tani te vetmet procedura qe ju keni pare kane qene ngjarjet te
shoqeruara me vegla (tools) te ndryshme. Shume aplikacione kane detyra te
cilat nuk jane te lidhura me objekte qe kerkojne rreshta kodi per te realizuar
keto detyra. Keto detyra zakonisht shkruhen ne nje general Sub procedure
(me fjale te tjera ne thelb njesoj si subroutine).
Duke perdorur Sub procedurat mund te ndani nje aplikacion kompleks ne
disa njesi kodi te menaxheshme. Kjo ju ndihmon per te arritur qellimet qe
permendem me siper: per ta bere kodin tuaj me te lexueshem dhe te
riperdorshem.
Percaktimi i nje Sub Procedure
Forma per nje Sub procedure te emertuar GenlSubProc eshte:
Sub GenlSubProc(Arguments) 'Seksioni i fillimit
.
End Sub
Seksioni i fillimit emerton Sub proceduren dhe percakton argumentat qe i
kalojne asaj. Argumentat jane nje liste e palimituar variablash te ndare
me presje, qe i kalojne procedures. Nqs ka argumenta, ath ata duhet te
deklarohen dhe te shkruhen ne seksionin e fillimit ne kete menyre:
Var1 As Type1, Var2 As Type2, ...
Shembull Sub Procedure:
Programim object-oriented Faqa 204
Me poshte eshte dhene kodi per nje Sub procedure (USMexConvert) e
cila pranon si te dhena hyrese (inputs ) nje shume ne dollar (USDollars)
dhe nje kurs kembimi (UStoLek). Si rezulatat (output) marrim nje shume
ne Lek (AlbLek).
Sub USMexConvert (USDollars As Single, UStoLek As Single, AlbLek As Single)
AlbLEk = UsDollars * UsToLek
End Sub
Programim object-oriented Faqa 205
Thirrja e nje Sub Procedure
Ka dy menyra per te thirrur nje Sub procedure.
Menyra 1:
Call GenlSubProc(Arguments) (nqs nuk ka argumenta, mos i
shkruani kllapat)
Menyra 2:
GenlSubProc Arguments
Pjesa me e madhe e programisteve ne Visual Basic perdorin Metoden 2.
Urrejne te shruajne kllapat!
Zgjidhni metoden me te cilen ndiheni me komod.
Shembull
Per te thirrur rutinen per shkembimin e dollarit, duhet te perdorim:
Call USMexConvert (USDollars, UStoLek, AlbLek)
Ose
USMexConvert USDollars, UStoLek, AlbLek
Programim object-oriented Faqa 206
Pozicionimi i Sub Procedures
Sub procedures mund te vendosen ne nje nga dy pozicionet ne
aplikacionin tuaj:
1. bashkangjitur nje form_e ose
2. bashkangjitur nje modul_i.
Vendosni nje procedure ne nje form nqs ajo ka lidhje specifike me
formen. E vendsoni ate ne nje modul nqs eshte nje procedure e
pergjithshme qe mund te perdoret nga nje forme tjeter apo nga nje modul
tjeter apo nga nje aplikacion tjeter.
Kudo qe ta vendosni proceduren ne nje forme apo modul, metodat e
krijimit te procedures jane te njejta. Zgjidhni ose hapni dritaren e kodit te
formes apo modulit. Sigurohuni qe ne kete dritare, lista Object te jete
(General) dhe lista Procedure te jete (Declarations). Tashme mund
te krijoni proceduren duke zgjedhur Add Procedure nga menuja Tools e
Visual Basic. Nje dritare shfaqet, dritare kjo ku ju lejohet te zgjidhni Type
Sub dhe te percaktoni nje emer per proceduren tuaj. Nje rruge tjeter per
te krijuar nje Sub eshte: shkoni ne rreshtin e fundit te seksionit General
Declarations, shkruani Sub te ndjekur nga nje hapesire dhe emrin e
procedures tuaj. Me pas shtypni Enter. Me secilen nga metodat per
krijimin e nje Sub, Visual Basic do te strukturoj nje template per
proceduren tuaj. Percaktoni aty listen e argumentave dhe shkruani kodin
tuaj ne Basic. Duke zgjedhur Insert Procedure nga menuja, ju mund te
zgjidhni nje tjeter opsion per proceduren tuaj: Scope. Ju mund te zgjidhni
nese procedura juaj eshte Public apo Private. Fjala scope shfaqet para
fjales Sub ne seksionin e percaktimit te procedures. Nqs nje module
procedure eshte Public, ai mund te thirret nga procedura te tjera ne
module te tjera. Nqs nje module procedure eshte Private, mund te thirret
vetem nga moduli ne te cilin eshte percaktuar. Theksojme, scope
Programim object-oriented Faqa 207
aplikohet vetem mbi procedurat ne module. Ne menyre standarte, te
gjitha procedurat ngjarje dhe general procedures ne nje forme jane
Private – ato mund te thirren vetem brenda formes. Ju duhet te percaktoni
scope te procedures tuaj.
Kalimi i argumentave ne një Sub Procedure
Kalimi i argumentave në një procedurë në VB bëhet “by reference”. Kjo
do të thotë që nëse një argument ndryshohet brenda procedurës, ai do të
mbetet i ndryshuar dhe pasi të dilet nga procedura.
Programuesit e C janë mësuar me konceptin e kalimit të argumentave
“by value”, ku një parameter i ndryshuar në një procedure do ta ruajë
vlerën që ka pasur para se të thirrej procedura. Visual Basic e suporton
dhe ketë metodë të kalimit të argumentave. Për këtë mjafton që të
vendoset fjala çelës ByVal përpara emrit të variablit në listën e
argumentave.
Programim object-oriented Faqa 208
Krijimi i nje Code Module
Nqs duhet te shkruani kod ne nje modul, ju nevoitet te dini me pare si te
krijoni dhe te ruani module. Nje menyre e mire per te menduar rreth
moduleve eshte ti konsideroni ato si forms_e pa objekte, vetem kod.
Per te krijuar nje modul, klikoni ne butonin New Module ne shiritin e
butonave, ose zgjidhni komanden Module nga menuja Insert. Ne kete
menyre, moduli shfaqet. Theksojme se modulet shfaqen ne Project
Window, ne vazhdim te form(s)_eve. Perdorni Project Window per te
levizur neper forms_e dhe module.
Sapo muduli te jete aktiv, krijoni te gjitha procedurat si u pershkruan me
siper. Per te emertuar modulin, klikoni ne dritaren properties (duhet qe
moduli te jete patjeter aktiv). Theksojme se Name eshte e vetmja veti
lidhur me nje modul. Ruajtja e nje moduli eshte e njejta gje si ruajtja e nje
forms_i – perdorni opsionet Save File dhe Save File As.
Programim object-oriented Faqa 209
Perdorimi i General Function ne Aplikacione
Sub procedures jane te lidhura me Function. Nje Function procedure, ose
thjesht Function, kryen nje detyre specifike brenda nje programi ne Visual
Basic dhe kthen nje vlere. Ne kemi pare disa funksione sic jane MsgBox dhe
Format.
Percaktimi i nje Funksioni
Forma e nje general Function te quajtur GenlFcn eshte:
Function GenlFcn(Arguments) As Type 'Seksioni i fillimit
.
.
GenlFcn = ...
End Function
Ne Seksionin e fillimit emertohet Function, specifikohet tipi (tipi i vleres
qe kthehet) dhe percaktohen Argumentat qe i kalojne funksionit.
Theksojme qe diku ne funksion, vlera e GenlFcn mund te llogaritet per tu
kthyer ne proceduren qe e therret.
Shembull Funksioni:
Me poshte eshte percaktuar nje funksion me emrin CylVol i cili llogarit
volumin e nje cilindri me te dhenat (Height) dhe (Radius).
Function CylVol(Height As Single, Radius As Single) As Single
Dim Area As Single
Const PI = 3.1415926
Area = PI * Radius ^ 2
Programim object-oriented Faqa 210
CylVol = Area * Height
End Sub
Thirrja e nje Function
Per te thirrur “call” apo perdorur nje Funksion, ju i shoqeroni nje
variabel (te te njejtin tip) Funskionit, me argumentat e tij. Kjo dmth, nqs
Funksioni GenlFunc eshte i tipit Integer, ath perdorni segmentin e kodit:
Dim RValue as Integer
.
.
RValue = GenlFunc(Arguments)
Shembull
Per te thirrur funksionin e llogaritjes se volumit, duhet te perdorim:
Dim Volume As Single
.
.
Volume = CylVol(Height, Radius)
Pozicionimi i Function Procedures
Si edhe Sub procedures, Functions mund te vendosen ne forms ose
modules. Krijohen duke perdorur ekzaktesisht te njejtin process te
pershkruar per Sub procedures, e vetmja diference eshte perdorimi i
fjales celes Function.
Dhe, ashtu si Sub procedures, Functions (ne module) mund te jene
Public ose Private.
Programim object-oriented Faqa 211
Shembull: Konvertimi i Temperatures
1. Hapni aplikacionin e Konvertimit te Temperatues nga leksionet me pare.
Theksojme se ne procedurat vsbTemp_Change dhe vsbTemp_Scroll,
ka shume pjese kodi qe perseriten. Ne do te zevendesojme kete kod me
nje Sub procedure qe printon vlerat dhe nje Function procedure qe ben
konvertimin e temperatures.
2. Shtoni nje modul ne aplikacionin tuaj. Krijoni nje Funksion (Public by
default) me emrin DegF_To_DegC.
Public Function DegF_To_DegC(DegF As Integer) As Integer
DegF_To_DegC = CInt((DegF - 32) * 5 / 9)
End Function
3. Kthehuni ne form_en tuaj. Krijoni nje Sub procedure me emrin
ShowTemps. Shkruani kodin, i cili perdor nje funksion te ri per te
konvertuar temperaturen dhe printon te dy vlerat ne kutite e etiketave
(label) respective.
Private Sub ShowTemps()
lblTempF.Caption = Str(TempF)
TempC = DegF_To_DegC(TempF)
lblTempC.Caption = Str(TempC)
End Sub
Programim object-oriented Faqa 212
Asnje argument nuk eshte i nevojshem meqe TempF dhe TempC jane
variabla global ne nivel forme.
4. Rishkruani procedurat vsbTemp_Change dhe vsbTemp_Scroll, te cilat
therrasin Sub procedure:
Private Sub vsbTemp_Change()
TempF = vsbTemp.Value
Call ShowTemps
End Sub
Private Sub vsbTemp_Scroll()
Call vsbTemp_Change
End Sub
Veme ne dukje se vsbTemp_Scroll therret vsbTemp_Change meqe
perdorin te njejtin kod. Ky eshte nje shembull i thirrjes se nje ngjarje
procedure.
5. Ruani aplikacionin dhe ekzekutojeni ate.
Programim object-oriented Faqa 213
Shembull: Image Viewer
1. Hapni aplikacionin Image Viewer nga leksionet e meparshme. Kodi per
ngjarjet cmdShow_Click dhe filImage_DblClick jane ekzaktesisht
njesoj. Fshini kodin ne proceduren filImage_DblClick dhe ne menyre
shume te thjeshte perdoreni ate duke thirrur proceduren
cmdShow_Click. Zevendesoni proceduren filImage_DblClick me:
Private Sub filImage_DblClick()
Call cmdShow_Click
End Sub
2. Ky eshte nje shembull tjeter i thirrjes se nje event procedure. Ruani
aplikacionin tuaj.
Programim object-oriented Faqa 214
Shtimi i menuve ne nje Aplikacion
Sic e kemi permendur me siper, eshte shume e rendesishme qe nderfaqesi i
aplikacionit tuaj te jete sa me familjar dhe konsistente per nje perdorues me
experience apo jo te Windows_it. Nje nja komponontet me familjare te nje
aplikacioni eshte Menu bar. Menute perdoren per ti siguruar perdoruesit
zgjedhje per te kontrolluar aplikacionin. Menute krijohen shume thjeshte ne
Visual Basic duke perdorur Menu Editor.
Nje menyre e mire per te menduar per elementet e struktures se nje menuje
eshte ti konsiderojme ato si nje liste hierarkike te command buttons te cilat
shfaqen kur hapim menu bar_in. Kur ju klikoni ne nje element te nje menuje,
nje detyre kryhet. Ashtu si command buttons, elementet e menuve
emertohen, kane captions si dhe kane properties.
Shembull
Me poshte jepet struktura e nje menuje tipike:
File Edit Format
New Cut Bold
Open Copy Italic
Save Paste Underline
Size
Exit 10
15
20
Programim object-oriented Faqa 215
Karakteret e nenvizuara jane celesa aksesi (access keys), njesoj si ne
command buttons. Niveli tregon pozicionin e nje elementi te menuse brenda
hierarkise. psh, New eshte nje sub-element ne menune File.
Vija nen Save ne menune File eshte nje ndares (ndan elementet e
menuse).
Me kete structure, Menu bar do te shfaq:
File Edit Format
Sub-menus shfaqen kur selektohet nje nga keto ‘top’ level element te
menuse. Sub-menu Size nen Format ka nje tjeter nivle ne hierarki. Eshte e
keshillueshme nga ana praktike te mos perdoren me shume se 2 nivelesh ne
menu. Cdo element i menuse do te kete nje Click event shoqeruar me te.
Menu Editor na lejon te percaktojme strukturen e menuse, te shtojme
celesa aksesi (access keys dhe shortcut keys), nqs deshirojme. Me pas
shtojme kodin ne ngjarje . Menu Editor zgjidhet nga menuja Tools ose duke
klikuar Menu Editor ne shiritin e butonave. Kjo gje do behet vetem nese
forma ku do te vendosim menune, eshte aktive. Sapo zgjedhim editorin, dhe
te hedhim shembullin e struktures se menuse, dritarja e editorit do te duket
si me poshte:
Programim object-oriented Faqa 216
Cdo element ne strukturen e menuse kerkon plotesimin e disa te dhenave
ne kete dritare.
1. Ne kutine Caption ju shkruani tekstin qe do te shfaqet ne menu
bar. Access keys jane percaktuar ne menyren standarte duke
perdorur shenjen (&). Separator bars (nje vije horizontale e cila
perdoret per te ndare elementet e menuse) percaktohen duke
percaktuar ne Caption shenjen (-). Kur percaktojme captions dhe
access keys, perpiquni ti perdorni ato konform standarteve te
Windows.
2. Ne kutine Name ju shkruani emrin e kontrollit per cdo element te
menuse. Kjo eshte analoge me vetine (property) Name te command
buttons dhe krijon Click event procedure per cdo element te
Programim object-oriented Faqa 217
menuse. Cdo element i menuse duhet te kete nje emer, edhe
separator bars! Prefiksi mnu perdoret per te emertuar elementet e
menuse. Elementet e Sub-menu_ve emertohen ne pergjithesi duke
iu referuar menuse kryesore ku ato bejne pjese. Psh, nqs elementi
New eshte nen menune kryesore File, perdorni emrin
mnuFileNew.
3. Kutia Index perdoret per te indeksuar elemente te menuve te
percaktuara si vektor kontrollesh.
4. Kutia dropdown Shortcut perdoret per ti percaktuar nje shortcut
ndonje elementi ne strukturen e menuse. Ky shortcut do te shfaqet
ne te djathte te caption te elementit te menuse. Nje shembull i tille
mund te permendetet shortcut_i Ctrl+X, per te prere nje tekst.
Cdo element menuje ka 4 properties te shoqeruara me te. Keto properties
mund te vendosen ne design time duke perdorur Menu Editor ose ne run-
time.
Keto properties jane:
Checked Perdoret per te treguar se kur nje opsion eshte
zgjdhur apo jo.
Enabled Nqs eshte True, elementi i menuse mund te
zgjidhet. Nqs eshte False, elementi i menuse
eshte ngjyre gri dhe nuk mund te zgjidhet.
Visible Percakton nese nje elementi i menuse shfaqet ne
strukture apo jo.
Programim object-oriented Faqa 218
WindowList Perdoret me Multiple Document Interface (MDI) –
diskutohet me vone.
Ne fund te formes se Menu Editor_it eshte nje list box ku shfaqet lista
hierarkike e elementeve te menuve. Elementet e Sub-menu jane te
zhvendosura ne te djathte te nivelit meme ne hierarki. Shigjetat me drejtim
djathtas dhe majtas percaktojne nivelet e elementeve te menuse, ndersa
shigjetat e drejtim lart dhe poshte ju lejojne te levizni elementet brenda te
njejtin nivel.
Butonat Next, Insert, dhe Delete perdoren per tu pozicionuar nje rresht
me poshte, per te shtuar nje rresht siper pozicionit korent, apo per te fshire
pozicionin korent.
Hidhni strukturen e menuse te marre me siper si shembull. Pasi te keni
hedhur kete structure, lista e plote ne fund te Menu Editor do te duket si me
poshte (Shenim: access keys tregohen nga shenja (&), shortcut keys jane
listuar ne te djathte dhe emrat jane treguar ne te majte – kjo pamje nuk
eshte si do te duket realisht ne Menu Editor; ato jane treguar vetem per te
ilustruar nje mundesi emertimi):
Programim object-oriented Faqa 219
Name
mnuFile &File
mnuFileNew .......&New
mnuFileOpen .......&Open
mnuFileSave .......&Save
mnuFileBar .......-
mnuFileExit .......E&xit
mnuEdit &Edit
mnuEditCut .......Cu&t Ctrl+X
mnuEditCopy .......&Copy Ctrl+C
mnuEditPaste .......&Paste Ctrl+V
mnuFmt F&ormat
mnuFmtBold .......Bold
mnuFmtItalic .......Italic
mnuFmtUnderline .......Underline
mnuFmtSize .......Size
mnuFmtSize10 ...............10
mnuFmtSize15 ...............15
mnuFmtSize20 ...............20
Programim object-oriented Faqa 220
Shembull 6-1
Note Editor
1. Start a new project. We will use this application the rest of this class. We
will build a note editor with a menu structure that allows us to control the
appearance of the text in the editor box. Since this is the first time we’ve
built menus, I’ll provide the steps involved.
2. Place a large text box on a form. Set the properties of the form and text
box:
Form1:
BorderStyle 1-Fixed Single
Caption Note Editor
Name frmEdit
Text1:
BorderStyle 1-Fixed Single
MultiLine True
Name txtEdit
ScrollBars 2-Vertical
Text [Blank]
Programim object-oriented Faqa 221
The form should look something like this when you’re done:
3. We want to add this menu structure to the Note Editor:
File Format
New Bold
Italic
Exit Underline
Size
Small
Medium
Large
Programim object-oriented Faqa 222
Note the identified access keys. Bring up the Menu Editor and assign the
following Captions, Names, and Shortcut Keys to each item. Make sure each
menu item is at is proper location in the hierarchy.
Caption Name Shortcut
&File mnuFile [None]
&New mnuFileNew [None]
- mnuFileBar [None]
E&xit mnuFileExit [None]
F&ormat mnuFmt [None]
& Bold mnuFmt Bold Ctrl+B
&Italic mnuFmtItalic Ctrl+I
&Underline mnuFmtUnderline Ctrl+U
&Size mnuFmtSize [None]
&Small mnuFmtSizeSmall Ctrl+S
&Medium mnuFmtSizeMedium Ctrl+M
&Large mnuFmtSizeLarge Ctrl+L
The Small item under the Size sub-menu should also be Checked to
indicate the initial font size. When done, look through your menu structure
in design mode to make sure it looks correct.
Programim object-oriented Faqa 223
With a menu, the form will appear like:
4. Each menu item that performs an action requires code for its Click event.
The only menu items that do not have events are the menu and sub-
menu headings, namely File, Format, and Size. All others need code. Use
the following code for each menu item Click event. (This may look like a
lot of typing, but you should be able to use a lot of cut and paste.)
If mnuFileNew is clicked, the program checks to see if the user really wants
a new file and, if so (the default response), clears out the text box:
Private Sub mnuFileNew_Click()
'If user wants new file, clear out text
Dim Response As Integer
Response = MsgBox("Are you sure you want to start a new file?", vbYesNo + vbQuestion, "New File")
If Response = vbYes Then txtEdit.Text = ""
End Sub
Programim object-oriented Faqa 224
If mnuFileExit is clicked, the program checks to see if the user really wants
to exit. If not (the default response), the user is returned to the program:
Private Sub mnuFileExit_Click()
'Make sure user really wants to exit
Dim Response As Integer
Response = MsgBox("Are you sure you want to exit the note editor?", vbYesNo + vbCritical + vbDefaultButton2, "Exit Editor")
If Response = vbNo Then
Exit Sub
Else
End
End If
End Sub
If mnuFmtBold is clicked, the program toggles the current bold status:
Private Sub mnuFmtBold_Click()
'Toggle bold font status
mnuFmtBold.Checked = Not (mnuFmtBold.Checked)
txtEdit.FontBold = Not (txtEdit.FontBold)
End Sub
Programim object-oriented Faqa 225
If mnuFmtItalic is clicked, the program toggles the current italic status:
Private Sub mnuFmtItalic_Click()
'Toggle italic font status
mnuFmtItalic.Checked = Not (mnuFmtItalic.Checked)
txtEdit.FontItalic = Not (txtEdit.FontItalic)
End Sub
If mnuFmtUnderline is clicked, the program toggles the current underline
status:
Private Sub mnuFmtUnderline_Click()
'Toggle underline font status
mnuFmtUnderline.Checked = Not (mnuFmtUnderline.Checked)
txtEdit.FontUnderline = Not (txtEdit.FontUnderline)
End Sub
If either of the three size sub-menus is clicked, indicate the appropriate
check mark location and change the font size:
Private Sub mnuFmtSizeSmall_Click()
'Set font size to small
mnuFmtSizeSmall.Checked = True
mnuFmtSizeMedium.Checked = False
mnuFmtSizeLarge.Checked = False
txtEdit.FontSize = 8
End Sub
Programim object-oriented Faqa 226
Private Sub mnuFmtSizeMedium_Click()
'Set font size to medium
mnuFmtSizeSmall.Checked = False
mnuFmtSizeMedium.Checked = True
mnuFmtSizeLarge.Checked = False
txtEdit.FontSize = 12
End Sub
Private Sub mnuFmtSizeLarge_Click()
'Set font size to large
mnuFmtSizeSmall.Checked = False
mnuFmtSizeMedium.Checked = False
mnuFmtSizeLarge.Checked = True
txtEdit.FontSize = 18
End Sub
5. Save your application. We will use it again in Class 6 where we’ll learn
how to save and open text files created with the Note Editor. Test out all
the options. Notice how the toggling of the check marks works. Try the
shortcut keys.
Programim object-oriented Faqa 227
Përdorimi i “Package & Deployment Wizard” për krijimin e paketës instaluese
1. Ju mund te ekzekutoni skedarin e ekzekutueshem të aplikimit “Editori i
shenimeve” meqënëse Visual Basic është i instaluar në kompjuterin
tuaj. Nuk do të kishit sukses nëse do të tentonit ta ekzekutoni atë
skedar në një kompjuter tjetër (ku Visual Basic nuk është i instaluar).
Ekzekutimi nuk është i mundur meqënëse në një kompjuter të tillë
mungojnë disa skedarë ndihmës të domosdoshëm (të quajtur ndryshe
“dynamic link libraries”. Këto skedarë mundësojnë lidhjen e
elementëve të ndryshëm të aplikimit dhe bëjnë që ai të funksionojë siç
duhet.
2. Për të mundësuar ekzekutimin e një aplikimi të ndërtuar në Visual
Basic në çdo kompjuter, është e nevojshme që krahas skedarit të
ekzekutueshëm të instalohen dhe skedarët e duhur ndihmës.
3. Visual Basic e zgjidh këtë problem të quajtur ndryshe si problemi i
shpërndarjes duke ofruar një mjet shumë të fuqishëm të quajtur
Package & Deployment Wizard. Ky mjet instalohet bashkë me
Visual Basic.
4. Package & Deployment Wizard përgatit paketën instaluese të aplikimit.
Ai ju ndihmon të përcaktoni se cilet janë skedarët e nevojshëm që
duhet të jenë pjesë e kësaj pakete, krijon programin Setup (të shkruar
në Visual Basic), që funksionon si të gjitha programet e tjera instaluese
të Windows (setup.exe), kompreson të gjithë skedarët e kërkuar për
të konsumuar sa më pak hapesirë të diskut, dhe i shkruan këto
skedarë në diskun përkatës (disketa, CD, flash disk, etj).
5. Për të ekzekutuar Package & Deployment Wizard, klikohet në butonin
Start të Windows, në folderin Visual Basic, Visual Basic Tools, dhe
zgjidhet Package & Deployment Wizard. Procedura përbëhet nga
disa hapa.
Programim object-oriented Faqa 228
Hapi 1. Informacioni fillestar. Përcaktoni emrin dhe rrugëkalimin e
projektit (.vbp). Klikoni në butonin Browse … për të zgjedhur skedarin e
duhur. Nëse skedari i ekzekutueshëm nuk është krijuar ende ose në
projekt janë bërë ndryshime pas krijimit të tiij ai do të krijohet në këtë
moment. Klikoni në butonin ‘Package’ për të vazhduar.
Hapi 2. Tipi i paketës. Zgjidhni Standard Setup Package (pasi do të
ndërtoni një paketë standarte instalimi). Klikoni në butonin Next për të
vazhduar.
Hapi 3. Folderi i paketës. Zgjidhni një direktori ku do të regjistroni
paketën instaluese. Klikoni në butonin Next për të vazhduar ose klikoni
në butonin Back për t’u kthyer në hapin e mëparshëm.
Programim object-oriented Faqa 229
Hapi 4. Skedarët e përfshirë. Package & Deployment Wizard do të
listojë të gjithë skedarët që ai mendon se janë të nevojshëm për
funksionimin ashtu siç duhet të aplikimit. Nëse aplikimi kërkon dhe
skedarë të tjerë të cilët nuk janë gjetur nga wizard-i (p.sh. skedarë të
jashëm të dhënash, të krijuar nga ju), ju mund t’i shtoni ato pasi të keni
klikuar në butonin Add. Klikoni në butonin Next për të vazhduar ose
klikoni në butonin Back për t’u kthyer në hapin e mëparshëm.
Hapi 5. Opsionet Cab. Skedarët e instalimit quhen ndryshe skedarë
“cab” (kanë prapashtesën cab). Ju mund të zgjidhni opsionin ‘Single cab
file’ nëse doni të krijoni një skedar të vetëm për ta kopjuar atë më pas në
një CD instaluese, ose ‘Multiple cab files’ për të krijuar disa disketa
instalimi. Nëse zgjidhni këtë të fundit ju duhet të përcaktoni dhe
kapacitetin e skedarëve. Klikoni në butonin Next për të vazhduar ose
klikoni në butonin Back për t’u kthyer në hapin e mëparshëm.
Hapi 6.Titulli i instalimit. Shkruani titullin që kërkoni të shfaqet gjatë
instalimit të aplikimit. Klikoni në butonin Next për të vazhduar ose klikoni
në butonin Back për t’u kthyer në hapin e mëparshëm.
Hapi 7. Elementet e menusë Start. Ky hap përcakton nëse pas
instalimit aplikimi juaj do të shfaqet në menunë Start. Klikoni në butonin
Next për të vazhduar ose klikoni në butonin Back për t’u kthyer në hapin
e mëparshëm.
Hapi 8. Vendi i instalimit. Wizard ju jep mundësinë të ndryshoni
vendndodhjen e skedarëve të instalimit. Klikoni në butonin Next për të
vazhduar ose klikoni në butonin Back për t’u kthyer në hapin e
mëparshëm.
Hapi 9. Skedarët e ndashëm. Disa skedarë në aplikimin tuaj mund të
përdoren dhe nga aplikime të tjera. Këto skedarë nuk do të fshihen nga
Programim object-oriented Faqa 230
sistemi në rast c’instalimi të aplikimit. Vendosni nëse keni apo jo skedarë
të tillë. Klikoni në butonin Next për të vazhduar ose klikoni në butonin
Back për t’u kthyer në hapin e mëparshëm.
Hapi 10. Fund! Caktoni emrin me të cilin do të ruhen të gjitha
zgjedhjet e bëra gjatë këtij proçesi. Klikoni në butonin Finish për të
vazhduar ose klikoni në butonin Back për t’u kthyer në hapin e
mëparshëm. Wizard-i do të krijojë dhe shkruaj skedarët cab dhe do t’ju
tregojë ku janë regjistruar ato. Klikoni në butonin Close. Do të ktheheni
në dritaren Package & Deployment Wizard. Klikoni në butonin Close.
Hapi 11. Shkrimi në median shpërndarëse. Ky nuk është një hap
i Wizard-it, por është një hap që duhet bërë nga vetë ju. Skedarët cab pasi
janë krijuar nga wizard-i duhet të kopjohen në CD ose disketat e
instalimit. Nëse keni krijuar një skedar të vetëm cab (për CD ROM),
kopjojeni këtë skedar, skedarin setup.exe si dhe skedarin setup.lst në CD
e instalimit. Nëse keni krijuar disa skedarë instalimi (për disa disketa)
kopjoni skedarët setup.exe, setup.lst, dhe skedarin e parë cab (emri i të
cilit mbaron me 1) në disketën numër 1. Kopjoni skedarin e dytë cab (emri
i të cilit mbaron me 2) në disketën numër 2, e kështu me rradhe.
Emërtoni disketat për të shmangur ngatërrimet.
Për të instaluar aplikimin me ndihmën e paketës instaluese të sapo krijuar,
pëdoruesi mjaftonë të vendosi CD ose disketën e parë në driver-in përkatës
dhe të ekzekutojë skedarin setup.exe. Më pas procedura është e njëjtë me
atë të instalimit të çdo produkti të Microsoft-it.
Programim object-oriented Faqa 231
Example 6-3
Note Editor - Creating a Distribution Disk
1. Open your Note Editor project again. Create a distribution disk using the
Package & Deployment Wizard.
2. Try installing the application on your computer. Better yet, take the disk
to another Windows 95/98/NT-based machine, preferably without Visual
Basic installed. Install the application using the distribution disk and test
its operation.
Programim object-oriented Faqa 232
Exercise 6
US Capitals Quiz
Develop an application that quizzes a user on states and capitals in the
United States. Use a menu structure that allows the user to decide whether
they want to name states or capitals and whether they want mulitple choice
or type-in answers. Throughly test your application. Design an icon for your
program using IconEdit or some other program. Create an executable file.
Create a distribution disk using the Application Setup Wizard. Give someone
your application disk and have them install it on their computer and try out
your nifty little program.
My Solution:
Form:
Programim object-oriented Faqa 233
Properties:
Form frmCapitals:
BorderStyle = 1 - Fixed Single
Caption = US Capitals
CommandButton cmdNext:
Caption = &Next Question
Enabled = False
CommandButton cmdExit:
Caption = E&xit
TextBox txtAnswer:
FontName = MS Sans Serif
FontSize = 13.2
Visible = False
Label lblComment:
Alignment = 2 - Center
BackColor = &H00C00000& (Blue)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 13.2
FontItalic = True
ForeColor = &H0000FFFF& (Yellow)
Programim object-oriented Faqa 234
Label lblScore:
Alignment = 2 - Center
AutoSize = True
BackColor = &H0000FFFF& (Yellow)
BorderStyle = 1 - Fixed Single
Caption = 0%
FontName = MS Sans Serif
FontSize = 15.6
FontBold = True
Label lblAnswer (control array):
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 13.2
Index = 0, 1, 2, 3
Label lblHeadAnswer:
Caption = Capital:
FontName = MS Sans Serif
FontSize = 13.2
FontBold = True
Programim object-oriented Faqa 235
Label lblHeadGiven:
Caption = State:
FontName = MS Sans Serif
FontSize = 13.2
FontBold = True
Menu mnuFile:
Caption = &File
Menu mnuFileNew:
Caption = &New
Menu mnuFileBar:
Caption = -
Menu mnuFileExit:
Caption = E&xit
Menu mnuOptions:
Caption = &Options
Menu mnuOptionsCapitals:
Caption = Name &Capitals
Checked = True
Menu mnuOptionsState:
Caption = Name &State
Menu mnuOptionsBar:
Programim object-oriented Faqa 236
Caption = -
Menu mnuOptionsMC:
Caption = &Multiple Choice Answers
Checked = True
Menu mnuOptionsType:
Caption = &Type In Answers
Code:
General Declarations:
Option Explicit
Dim CorrectAnswer As Integer
Dim NumAns As Integer, NumCorrect As Integer
Dim Wsound(26) As Integer
Dim State(50) As String, Capital(50) As String
SoundEx General Function (this is a neat little function to check if spelling of
two words is similar):
Private Function SoundEx(W As String, Wsound() As Integer) As String
‘Generates Soundex code for W
‘Allows answers whose spelling is close, but not exact
Programim object-oriented Faqa 237
Dim Wtemp As String, S As String
Dim L As Integer, I As Integer
Dim Wprev As Integer, Wsnd As Integer, Cindex As Integer
Wtemp = UCase(W)
L = Len(W)
If L <> 0 Then
S = Left(Wtemp, 1)
Wprev = 0
If L > 1 Then
For I = 2 To L
Cindex = Asc(Mid(Wtemp, I, 1)) - 64
If Cindex >= 1 And Cindex <= 26 Then
Wsnd = Wsound(Cindex) + 48
If Wsnd <> 48 And Wsnd <> Wprev Then S = S + Chr(Wsnd)
Wprev = Wsnd
End If
Next I
End If
Else
S = ""
End If
SoundEx = S
End Function
Update_Score General Procedure:
Private Sub Update_Score(Iscorrect As Integer)
Programim object-oriented Faqa 238
Dim I As Integer
'Check if answer is correct
cmdNext.Enabled = True
cmdNext.SetFocus
If Iscorrect = 1 Then
NumCorrect = NumCorrect + 1
lblComment.Caption = "Correct!"
Else
lblComment.Caption = "Sorry ..."
End If
'Display correct answer and update score
If mnuOptionsMC.Checked = True Then
For I = 0 To 3
If mnuOptionsCapitals.Checked = True Then
If lblAnswer(I).Caption <> Capital(CorrectAnswer) Then
lblAnswer(I).Caption = ""
End If
Else
If lblAnswer(I).Caption <> State(CorrectAnswer) Then
lblAnswer(I).Caption = ""
End If
End If
Next I
Else
If mnuOptionsCapitals.Checked = True Then
txtAnswer.Text = Capital(CorrectAnswer)
Else
Programim object-oriented Faqa 239
txtAnswer.Text = State(CorrectAnswer)
End If
End If
lblScore.Caption = Format(NumCorrect / NumAns, "##0%")
End Sub
cmdExit Click Event:
Private Sub cmdExit_Click()
'Exit program
Call mnuFileExit_Click
End Sub
cmdNext Click Event:
Private Sub cmdNext_Click()
'Generate the next question
cmdNext.Enabled = False
Call Next_Question(CorrectAnswer)
End Sub
Form Activate Event:
Private Sub Form_Activate()
Call mnufilenew_click
Programim object-oriented Faqa 240
End Sub
Form Load Event:
Private Sub Form_Load()
Randomize Timer
'Load soundex function array
Wsound(1) = 0: Wsound(2) = 1: Wsound(3) = 2: Wsound(4) = 3
Wsound(5) = 0: Wsound(6) = 1: Wsound(7) = 2: Wsound(8) = 0
Wsound(9) = 0: Wsound(10) = 2: Wsound(11) = 2: Wsound(12) = 4
Wsound(13) = 5: Wsound(14) = 5: Wsound(15) = 0: Wsound(16) = 1
Wsound(17) = 2: Wsound(18) = 6: Wsound(19) = 2: Wsound(20) = 3
Wsound(21) = 0: Wsound(22) = 1: Wsound(23) = 0: Wsound(24) = 2
Wsound(25) = 0: Wsound(26) = 2
'Load state/capital arrays
State(1) = "Alabama": Capital(1) = "Montgomery"
State(2) = "Alaska": Capital(2) = "Juneau"
State(3) = "Arizona": Capital(3) = "Phoenix"
State(4) = "Arkansas": Capital(4) = "Little Rock"
State(5) = "California": Capital(5) = "Sacramento"
State(6) = "Colorado": Capital(6) = "Denver"
State(7) = "Connecticut": Capital(7) = "Hartford"
State(8) = "Delaware": Capital(8) = "Dover"
State(9) = "Florida": Capital(9) = "Tallahassee"
State(10) = "Georgia": Capital(10) = "Atlanta"
State(11) = "Hawaii": Capital(11) = "Honolulu"
State(12) = "Idaho": Capital(12) = "Boise"
State(13) = "Illinois": Capital(13) = "Springfield"
State(14) = "Indiana": Capital(14) = "Indianapolis"
Programim object-oriented Faqa 241
State(15) = "Iowa": Capital(15) = "Des Moines"
State(16) = "Kansas": Capital(16) = "Topeka"
State(17) = "Kentucky": Capital(17) = "Frankfort"
State(18) = "Louisiana": Capital(18) = "Baton Rouge"
State(19) = "Maine": Capital(19) = "Augusta"
State(20) = "Maryland": Capital(20) = "Annapolis"
State(21) = "Massachusetts": Capital(21) = "Boston"
State(22) = "Michigan": Capital(22) = "Lansing"
State(23) = "Minnesota": Capital(23) = "Saint Paul"
State(24) = "Mississippi": Capital(24) = "Jackson"
State(25) = "Missouri": Capital(25) = "Jefferson City"
State(26) = "Montana": Capital(26) = "Helena"
State(27) = "Nebraska": Capital(27) = "Lincoln"
State(28) = "Nevada": Capital(28) = "Carson City"
State(29) = "New Hampshire": Capital(29) = "Concord"
State(30) = "New Jersey": Capital(30) = "Trenton"
State(31) = "New Mexico": Capital(31) = "Santa Fe"
State(32) = "New York": Capital(32) = "Albany"
State(33) = "North Carolina": Capital(33) = "Raleigh"
State(34) = "North Dakota": Capital(34) = "Bismarck"
State(35) = "Ohio": Capital(35) = "Columbus"
State(36) = "Oklahoma": Capital(36) = "Oklahoma City"
State(37) = "Oregon": Capital(37) = "Salem"
State(38) = "Pennsylvania": Capital(38) = "Harrisburg"
State(39) = "Rhode Island": Capital(39) = "Providence"
State(40) = "South Carolina": Capital(40) = "Columbia"
State(41) = "South Dakota": Capital(41) = "Pierre"
Programim object-oriented Faqa 242
State(42) = "Tennessee": Capital(42) = "Nashville"
State(43) = "Texas": Capital(43) = "Austin"
State(44) = "Utah": Capital(44) = "Salt Lake City"
State(45) = "Vermont": Capital(45) = "Montpelier"
State(46) = "Virginia": Capital(46) = "Richmond"
State(47) = "Washington": Capital(47) = "Olympia"
State(48) = "West Virginia": Capital(48) = "Charleston"
State(49) = "Wisconsin": Capital(49) = "Madison"
State(50) = "Wyoming": Capital(50) = "Cheyenne"
End Sub
lblAnswer Click Event:
Private Sub lblAnswer_Click(Index As Integer)
'Check multiple choice answers
Dim Iscorrect As Integer
'If already answered, exit
If cmdNext.Enabled = True Then Exit Sub
Iscorrect = 0
If mnuOptionsCapitals.Checked = True Then
If lblAnswer(Index).Caption = Capital(CorrectAnswer) Then Iscorrect = 1
Else
If lblAnswer(Index).Caption = State(CorrectAnswer) Then Iscorrect = 1
End If
Call Update_Score(Iscorrect)
Programim object-oriented Faqa 243
End Sub
mnuFileExit Click Event:
Private Sub mnuFileExit_Click()
'End the application
End
End Sub
mnuFileNew Click Event:
Private Sub mnufilenew_click()
'Reset the score and start again
NumAns = 0
NumCorrect = 0
lblScore.Caption = "0%"
lblComment.Caption = ""
cmdNext.Enabled = False
Call Next_Question(CorrectAnswer)
End Sub
mnuOptionsCapitals Click Event:
Private Sub mnuOptionsCapitals_Click()
'Set up for providing capital, given state
mnuOptionsState.Checked = False
Programim object-oriented Faqa 244
mnuOptionsCapitals.Checked = True
lblHeadGiven.Caption = "State:"
lblHeadAnswer.Caption = "Capital:"
Call mnufilenew_click
End Sub
mnuOptionsMC Click Event:
Private Sub mnuOptionsMC_Click()
'Set up for multiple choice answers
Dim I As Integer
mnuOptionsMC.Checked = True
mnuOptionsType.Checked = False
For I = 0 To 3
lblAnswer(I).Visible = True
Next I
txtAnswer.Visible = False
Call mnufilenew_click
End Sub
mnuOptionsState Click Event:
Private Sub mnuOptionsState_Click()
'Set up for providing state, given capital
mnuOptionsState.Checked = True
Programim object-oriented Faqa 245
mnuOptionsCapitals.Checked = False
lblHeadGiven.Caption = "Capital:"
lblHeadAnswer.Caption = "State:"
Call mnufilenew_click
End Sub
mnuOptionsType Click Event:
Private Sub mnuOptionsType_Click()
'Set up for type in answers
Dim I As Integer
mnuOptionsMC.Checked = False
mnuOptionsType.Checked = True
For I = 0 To 3
lblAnswer(I).Visible = False
Next I
txtAnswer.Visible = True
Call mnufilenew_click
End Sub
Next_Question General Procedure:
Private Sub Next_Question(Answer As Integer)
Dim VUsed(50) As Integer, I As Integer, J As Integer
Dim Index(3)
lblComment.Caption = ""
NumAns = NumAns + 1
'Generate the next question based on selected options
Programim object-oriented Faqa 246
Answer = Int(Rnd * 50) + 1
If mnuOptionsCapitals.Checked = True Then
lblGiven.Caption = State(Answer)
Else
lblGiven.Caption = Capital(Answer)
End If
If mnuOptionsMC.Checked = True Then
'Multiple choice answers
'Vused array is used to see which states have
'been selected as possible answers
For I = 1 To 50
VUsed(I) = 0
Next I
'Pick four different state indices (J) at random
'These are used to set up multiple choice answers
'Stored in the Index array
I = 0
Do
Do
J = Int(Rnd * 50) + 1
Loop Until VUsed(J) = 0 And J <> Answer
VUsed(J) = 1
Index(I) = J
I = I + 1
Loop Until I = 4
Programim object-oriented Faqa 247
'Now replace one index (at random) with correct answer
Index(Int(Rnd * 4)) = Answer
'Display multiple choice answers in label boxes
For I = 0 To 3
If mnuOptionsCapitals.Checked = True Then
lblAnswer(I).Caption = Capital(Index(I))
Else
lblAnswer(I).Caption = State(Index(I))
End If
Next I
Else
'Type-in answers
txtAnswer.Locked = False
txtAnswer.Text = ""
txtAnswer.SetFocus
End If
End Sub
txtAnswer KeyPress Event:
Private Sub txtAnswer_KeyPress(KeyAscii As Integer)
'Check type in answer'
Dim Iscorrect As Integer
Dim YourAnswer As String, TheAnswer As String
'Exit if already answered
If cmdNext.Enabled = True Then Exit Sub
If (KeyAscii >= vbKeyA And KeyAscii <= vbKeyZ) _
Programim object-oriented Faqa 248
Or (KeyAscii >= vbKeyA + 32 And KeyAscii <= vbKeyZ + 32) _
Or KeyAscii = vbKeySpace Or KeyAscii = vbKeyBack Or KeyAscii = vbKeyReturn Then
'Acceptable keystroke
If KeyAscii <> vbKeyReturn Then Exit Sub
'Lock text box once answer entered
txtAnswer.Locked = True
Iscorrect = 0
'Convert response and correct answers to all upper
'case for typing problems
YourAnswer = UCase(txtAnswer.Text)
If mnuOptionsCapitals.Checked = True Then
TheAnswer = UCase(Capital(CorrectAnswer))
Else
TheAnswer = UCase(State(CorrectAnswer))
End If
'Check for both exact and approximate spellings
If YourAnswer = TheAnswer Or _
SoundEx(YourAnswer, Wsound()) = SoundEx(TheAnswer, Wsound()) Then Iscorrect = 1
Call Update_Score(Iscorrect)
Else
'Unacceptable keystroke
KeyAscii = 0
End If
End Sub
Programim object-oriented Faqa 249
7. Identifikuesi i gabimeve,
Debugging dhe File Input/Output
Ne kete kapitull, do te thellojme njohurite tona ne Visual Basic duke shqyrtuar disa tema te reja. Fillimisht do te shohim identifikuesin e gabimeve ne program, duke perdorur te dy teknikat, gjurmimin e gabimeve ne kohen e ekzekutimit (run-time error) dhe korrigjimin. Me pas do te shohim futjen e te dhenave (input) dhe daljen e tyre (output) ne disqe duke perdorur skedaret sekuencial dhe skedaret me akses te rastesishem.
Llojet e gabimeve
Pavaresisht se sa shume ne perpiqemi, gabimet ndodhin ne programet tona. Keto gabime mund te grupohen ne tre kategori:
1. Gabime Sintaksore (Syntax errors)2. Gabime te Ekzekutimit (Run-time errors)3. Gabime Logjike (Logic errors)
Syntax errors ndodhin kur shkruani gabim nje komande apo harroni nje fjalse apo argument. Visual Basic gjen keto gabime sapo ato ndeshen dhe ju ofron ndihme per ti korigjuar ato. Nuk mund te ekzekutoni nje program ne Visual Basic derisa te gjithe gabimet sintaksore te jene korigjuar
Run-time errors ne pergjithesi jane jashte kontrollit te programit tuaj. Mund te permendim: kur nje variable merr nje vlere te paparashikuar (pjesetimi me zero), kur porta e nje driver_i lihet e hapur, apo kur nje skedar nuk gjendet. Visual Basic ju lejon “te zini ne gracke” (ngrini kurthe) ketyre lloj gabimeve dhe ju mundeson identifikimin e tyre.
Logic errors jane gabimet me te veshtira per ti gjetur. Me gabimet logjike, ne pergjithesi programi ekzekutohet, por do te japi nje rezultat te gabuar apo te paparashikuar. Korrigjuesi i Visual Basic ju ndihmone ne zbulimin dhe gjetjen e gabimeve logjike.
Programim object-oriented Faqa 250
Disa menyra per te ulur numrin e gabimeve:
Dizenjoni aplikacionin tuaj me kujdes. Me shume kohe eharxhuar ne dizenjim do te thote me pak kohe per debugging.
Perdorni komentet ku jane te zbatueshme. Komentet ju vijne ne ndihme per te kujtuar se cfare jeni perpjekur te beni.
Perdorni emertime te qendryeshme dhe me kuptim per variablat, objektet dhe procedurat.
Gjurmimi dhe korigjimi i gabimeve Run-Time
Gabimet Run-time jane te gjurmueshme. Kjo do te thote se Visual Basic njeh nje gabim sapo ai ndodh duke ju dhene mundesine ta gjurmoni ate dhe te kryeni veprimet per trajtimin e tij. Nqs nje gabim ndodh dhe nuk gjurmohet, programi juaj zakonisht do te mbyllet ne nje menyre te thjeshte (jo ‘zyrtarisht’ nga ana juaj).
Gjurmimi i gabimeve mundesohet me shprehjen On Error:
On Error GoTo errlabel
Sic shihet perdoret shprehja GoTo. Ne kohen kur nje gabim run-time ndodh duke ndejur kete rresht kontrolli I programit transferohet ne rreshtin me etiketen errlabel. Risjellja e rreshtit te etiketuar eshte thjesht nje rresht me etikete (emertim) ndjekur nga dy pika (:).
Menyra me e mire per te shpjeguar se sit e gjurmojme gabimet eshte te shohim skicen e nje shembulli procedure me gjurmim gabimesh.
Sub SubExample()
.
. [Declare variables, ...]
.
On Error GoTo HandleErrors
.
. [Procedure code]
Programim object-oriented Faqa 251
.
Exit Sub
HandleErrors:
.
. [Error handling code]
.
End Sub
Ne kohen kur keni filluar te deklaroni variablat, percaktoni konstantet dhe ndonje element tjeter te procedurave paraprake, shprehja On Error eshte ekzekutuar per te mundesuar gjurmimin e gabimeve. Kjo shprehje ndiqet nga kodi I zakonshem i procedures. Kodi per identifikimin e gabimeve shkon ne fund te procerdures, shoqeruar me etiketen e shprehjes HandleErrors. Ky eshte kodi qe ekzekutohet nqs nje gabim ndodh kudoqofte ne Sub procedure. Theksojme se per te shmangur ekzekutimin e paqellimshem te kodit per identifikimin e gabimeve ju duhet te dilni nga kodi (me Exit Sub).
Meqenese kodi per identifikimin e gabimit eshte ne te njejten procedure ku gabimi ndodh, gjithe variablat ne ate procerdure jane ne dispozicion per veprime te mundshme korigjimi. Nqs ndonje here ne proceduren tuaj, doni te mbyllni gjurmimin e gabimeve (turn off error trapping), duhet te shkruani shprehjen ne vazhdim:
On Error GoTo 0
Sapo nje gabim run-time ndodh, ne duam te dime se kush eshte gabimi dhe tentojme ta riparojme ate. Kjo behet me ane te kodit te identifikimit te gabimit (error handling code).Visual Basic ofron ndihme ne identifikimin e gabimeve run-time. Objekti Err kthen ne vetine e tij Number (Err.Number), numrin qe lidhet me gabimin actual. (Funksioni Err ka veti te tjera shume te dobishme qe ne nuk do ti trajtojme ne kete cikel leksionesh – konsultohuni ne ndihmen on-line per informacione te metejshme.) Funksioni Error() merr kete numer gabimi si argument te tij dhe kthen nje pershkrim te gabimit. Konsultohuni me ndihmen on-line per numrat dhe pershkrimet e gabimeve run-time ne Visual Basic.
Programim object-oriented Faqa 252
Sapo gjurmohet nje gabim dhe merret ndonje veprim, kontrolli duhet te rikthehet ne aplikacionin tuaj. Ky kontroll kthehet nepermjet shprehjes Resume. Ka tre alternativa (opsione):
Resume Ju lejon te rigjykoni veprimin qe shkaktoi gabimin. Kjo do te thote qe kontrolli kthehet ne rreshtin ku ndodhi gabimi. Kjo mund te jete e rrezikshme nqs gabimi nuk eshte riparuar (nepermjet kodit apo perdoruresit), dhe rezultati mund te jete nje cikel pafund ndermjet identifikuesit te gabimit dhe kodit te procedures.
Resume NextKontrolli i programit kthehet ne rreshtin pasardhes te rreshtit ku ndodhi gabimi.
Resume label Kontrolli i programit kthehet ne rreshtin me etikete label.
Kini kujdes me shprehjen Resume. Kur ekzekutoni pjesen e kodit te identifikimit te gabimit dhe fundi i procedures ndeshet para nje Resume, do te ndodhi nje gabim. Gjithashtu, nqs nje Resume ndeshet jashte pjeses se kodit per identifikimin e gabimit, nje gabim ndodh.
General Error Handling Procedure
Zhvillimi I nje procedure te pershtatshme per identifikimin e gabimeve (error handling procedure) eshte ne vartesi nga aplikacioni. Ju duhet te dini se per cfare lloj gabimesh jeni duke kerkuar dhe cfare veprimesh korrigjuese duhet te perdoren nqs keto gabime ndeshen. Psh, nqs gjendet nje ‘pjestim me zero’, ju duhet te vendosni nese do ta kaperceni veprimin apo jo. Ajo qe krijojme (zhvillojme, paraqesim) ketu eshte nje sistem i pergjithshem per nje procedure te identifikimit te gabimit. Ai thjesht njofton perdoruesin per ndeshjen e nje gabimi, jep nje pershkrim te gabimit dhe lejon perdoruesin te , Abort, Retry, apo Ignore. Ky sistem eshte nje pike e mire fillimi per percaktimin (projektimin) e identifikuesit te gabimeve nga ana e perdoruesit ne aplikacionin tuaj.Kodi I pergjithshem (I cili fillon me etiketen HandleErrors) eshte:
HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))
Programim object-oriented Faqa 253
Case vbAbort
Resume ExitLine
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
ExitLine:
Exit Sub
Le te shikojme me hollesisht se cfare ndodh ne kete pjese kodi. Fillimisht, kjo rutine ekzekutohet vetem nqs ndodh nje gabim. Do te shfaqet nje message box, I cili perdor si mesazh pershkrimin e gabimit [Error(Err.Number)], perdor nje ikone kritike (critical icon) se bashku me butonat Abort, Retry, dhe Ignore, dhe perdor si titull numrin e gabimit [Err.Number]. Ky message box kthen nje pergjigje qe tregon se cili nga butonat eshte zgjedhur nga perdoruesi. Nqs eshte zgjedhur butoni Abort, thjesht dilet nga procedura Kjo behet duke perdorur Resume ne rreshtin me etikete ExitLine). Nqs eshte zgjedhur butoni Retry, athere rreshti I cenuar do te riprovohet per tu ekzekutuar (ne nje aplikacion real, ju apo perdoruesi ketu duhet te beje ndonje ndryshim per te korigjuar kushtin qe shkakton gabimin). Nqs eshte zgjedhur butoni Ignore, programi do te vazhdoje te funksionoje me rreshtin qe pason rreshtin qe shkaktoi gabimin.
Per perdorimin e ketij kodi te pergjithshem ne nje procedure ekzistuese, duhet te beni tre gjera:
1. Kopjoni dhe ngjisni (Copy – paste) kodin per identifikimit te gabimit ne fund te procedures tuaj.
2. Para rreshtit me etikete HandleErrors vendosni nje rresht Exit Sub.
Programim object-oriented Faqa 254
3. Ne fillim te procedures tuaj vendosni rreshtin On Error GoTo HandleErrors.
Psh, nqs procedura juaj eshte SubExample te cilen e pame me siper, kodi I ndryshuar do te jete si me poshte:
Sub SubExample()
.
. [Declare variables, ...]
.
On Error GoTo HandleErrors
.
. [Procedure code]
.
Exit Sub
HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))
Case vbAbort
Resume ExitLine
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
ExitLine:
Exit Sub
Programim object-oriented Faqa 255
End Sub
Ritheksojme qe kjo eshte nje rutine baze shume e mire per identifikimin e gabimeve. Ju mund ta perdorni ate ne aplikacionin tuaj dhe te beni ndryshimet e nevojshme. Ne menyre te vecante, ju duhet kodi per te pastruar kushtet qe shkaktojne babime perpara se te perdorni opsionin Retry.
Dhe se fundmi, pasi shkruani nje rutine per identifikimin e gabimeve, ju duhet ta testoni ate per tu siguruar qe ajo funksionon vertet. Por krijimi I gabimeve run-time ndonjehere eshte e veshtire, ndofta dhe e rrezikshme.
Visual Basic vjen ne ndihme!
Visual Basic i bashkangjit objektit Err nje metode (Raise) e cila simulon rastisjen e nje gabimi run-time error. Per te shkaktuar nje gabim me vlere Number, perdorni:
Err.Raise Number
Ne mund te perdorim kete funksion per te testuar plotesisht (krejtesisht) operimin e ndonje identifikuesi gabimi qe ne shkruajme. Pasi testimi perfundon duhet te hiqni shprehjen Raise.
Per te pastruar nje kusht gabim (cilindo gabim, jo vetem ato qe gjenerohen nga metoda Raise), perdorni metoden Clear:
Err.Clear
Programim object-oriented Faqa 256
Shembull 7-1
Gjurmim i thjeshte gabimi
1. Hapni nje project te ri. Shtoni nje text box dhe nje command button.
2. Vendosni vetite e formes dhe secilit kontroll si me poshte:
Form1:
BorderStyle 1-Fixed Single
Caption Error Generator
Name frmError
Command1:
Caption Generate Error
Default True
Name cmdGenError
Text1:
Name txtError
Text [Blank]
Forma do te kete pamje te ngjashme me:
Programim object-oriented Faqa 257
3. Bashkangjisni kodin me poshte ne ngjarjen cmdGenError_Click.
Private Sub cmdGenError_Click()
On Error GoTo HandleErrors
Err.Raise Val(txtError.Text)
Err.Clear
Exit Sub
HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))
Case vbAbort
Resume ExitLine
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
ExitLine:
Exit Sub
End Sub
Programim object-oriented Faqa 258
Ne kete kod thjesht gjenerohet nje gabim duke perdorur numrin e future ne text box. Me pas identifikuesi baze I gabimit shfaq nje message box te cilit ju mund ti pergjigjeni ne nje nga tre menyrat.
4. Ruani aplikacionin. Provojeni ate duke perdorur disa nga keto numra tipike gabimesh (ose perdorni numrat qe mund ti gjeni ne ndihmen on-line). Vereni se si kontrolli I prpgramit do te bdryshoje ne varesi te butonit qe ju do te klikoni.
Numer Gabimi Pershkrimi I Gabimit
6 Overflow
9 Subscript out of range
11 Division by zero
13 Type mismatch
16 Expression too complex
20 Resume without error
52 Bad file name or number
53 File not found
55 File already open
61 Disk full
70 Permission denied
92 For loop not initialized
Programim object-oriented Faqa 259
Korrigjimi i programeve ne Visual Basic
Le te shikojme se si mund te kerkojme dhe eleminojme gabimet logjike (logical errors) Ne Këto janë gabime që nuk e pengojne aplikacionin te ekzekutohet, por të shkaktojnë rezultate të pasakta apo të papritura. Visual Basic ofron një grup me mjete per debugging për të ndihmuar në kërkimin e ketyre gabimeve.
Te beni Debugging një kodi është art, jo shkencë. Për të eliminuar të gjitha gabimet logjike në programin tuaj nuk ka procese të përcaktuara të cilat ju duhet ti ndiqni . Qasja e zakonshme është të eliminohen ato gabime sapo te zbulohen.
Ajo që ne do të bëjmë është: te tregojme veglat (mjetet) debugging qe jane ne dispozicion në mjedis e Visual Basic (disa prej të cilave dukent si butona në shiritin e veglave) dhe te përshkruajmë përdorimin e seciles prej tyre me një shembull.
Nderfaqa ndermjet aplikacionit tuaj dhe veglave te korrigjimit eshte nepermjet 3 dritareve te ndryshme korigjimi : Immediate Window, Locals Window, dhe Watch Window. Keto dritare mund te aksesohen nga menuja View (Immediate Window mund te aksesohet duke shtypur nga tastiera Ctrl+G). Ose, ato mund te zgjidhen nga Shiriti I Veglave (Toolbar–i) Debug (ky toolbar aksesohet duke perdorur opsionin Toolbars te menuse View):
Te gjitha korrigjimet qe behen duke perdorur dritaren Debug behen kur aplikacioni eshte ne break mode. Ju mund te filloni break mode duke vendosur pika thyerjeje me klikim te Ctrl+Break, ose programi do te kaloje ne break mode nqs:
has ne nje gabim te pagjurmuar ose shpehjen Stop.
Programim object-oriented Faqa 260
Immediate WatchLocals
Sapo te jeni ne break mode, dritarja e debug-ut dhe mjetet e tjera mund te perdoren per:
Percaktimin e vlerave te variablave Vendosjen e pikave te thyerjes Vendosjen e vrojtimit te variablave dhe shprehjeve Kontroll manual te aplikacionit Percaktimin se kush procedure eshte thirrur Ndryshim te vlerave dhe vetive te variablave
Shembull 6-2
Shembull Korrigjimi
1. Ndryshe nga shembujt e tjere, kete shembull do ta bejme si nje grup. Ai do te perdoret per te paraqitur (demostruar) perdorimin e veglave te korrigjimit (debugging tools).
2. Shembulli ka thjesht nje form dhe nje buton te vetem. Butoni perdoret per te ekzekutuar nje kode.
3. Kodi qe I bashkangjitet ngjarjes Click te ketij butoni eshte nje cikel i thjeshte I cili vlereson nje funksion me disa vlera.
Private Sub Command1_Click()
Dim X As Integer, Y As Integer
X = 0
Do
Y = Fcn(X)
Programim object-oriented Faqa 261
X = X + 1
Loop While X <= 20
End Sub
Ky kod fillon me nje vlere X = 0 dhe llogarit vleren Y duke perdorur funksionin e pergjithshem integer Fcn. Me pas rrit vleren e X me 1 dhe perserit ciklin (Loop). Kodi vazhdon ciklin derisa X te jete me I vogel ose I barabarte me 20. Funksioni Fcn llogaritet duke perdorur:
Function Fcn(X As Integer) As Integer
Fcn = CInt(0.1 * X ^ 2)
End Function
Padyshim, ky kod nuk ben shume gjera, vecanerisht pa ndonje perfundim, por ai eshte nje shembull I mire per te pare perdorimin e korrigjuesit. Ndertoni aplikacionin dhe behuni gati per te provuar korrigjimin.
Programim object-oriented Faqa 262
Using the Debugging Tools
There are several debugging tools available for use in Visual Basic. Access to these tools is provided with both menu options and buttons on the Debug toolbar. These tools include breakpoints, watch points, calls, step into, step over, and step out.
The simplest tool is the use of direct prints to the immediate window.
Printing to the Immediate Window:
You can print directly to the immediate window while an application is running. Sometimes, this is all the debugging you may need. A few carefully placed print statements can sometimes clear up all logic errors, especially in small applications.
To print to the immediate window, use the Print method:
Debug.Print [List of variables separated by commas or semi-colons]
Debug.Print Example:
1. Place the following statement in the Command1_Click procedure after the line calling the general procedure Fcn:
Debug.Print X; Y
and run the application.
Programim object-oriented Faqa 263
2. Examine the immediate window. Note how, at each iteration of the loop, the program prints the value of X and Y. You could use this information to make sure X is incrementing correctly and that Y values look acceptable.
3. Remove the Debug.Print statement.
Breakpoints:
In the above examples, the program ran to completion before we could look at the debug window. In many applications, we want to stop the application while it is running, examine variables and then continue running. This can be done with breakpoints.
A breakpoint is a line in the code where you want to stop (temporarily) the execution of the program, that is force the program into break mode. To set a breakpoint, put the cursor in the line of code you want to break on. Then, press <F9> or click the Breakpoint button on the toolbar or select Toggle Breakpoint from the Debug menu. The line will be highlighted.
When you run your program, Visual Basic will stop when it reaches lines with breakpoints and allow you to use the immediate window to check variables and expressions. To continue program operation after a breakpoint, press <F5>, click the Run button on the toolbar, or choose Start from the Run menu.
You can also change variable values using the immediate window. Simply type a valid Basic expression. This can sometimes be dangerous, though, as it may change program operation completely.
Programim object-oriented Faqa 264
Breakpoint Example:
1. Set a breakpoint on the X = X + 1 line in the sample program. Run the program.
2. When the program stops, display the immediate window and type the following line:
Print X;Y
3. The values of these two variables will appear in the debug window. You can use a question mark (?) as shorthand for the command Print, if you’d like. Restart the application. Print the new variable values.
4. Try other breakpoints if you have time. Once done, all breakpoints can be cleared by Ctrl+Shift+<F9> or by choosing Clear All Breakpoints from the Debug menu. Individual breakpoints can be toggled using <F9> or the Breakpoint button on the toolbar.
Programim object-oriented Faqa 265
Viewing Variables in the Locals Window:
The locals window shows the value of any variables within the scope of the current procedure. As execution switches from procedure to procedure, the contents of this window changes to reflect only the variables applicable to the current procedure. Repeat the above example and notice the values of X and Y also appear in the locals window.
Watch Expressions:
The Add Watch option on the Debug menu allows you to establish watch expressions for your application. Watch expressions can be variable values or logical expressions you want to view or test. Values of watch expressions are displayed in the watch window.
In break mode, you can use the Quick Watch button on the toolbar to add watch expressions you need. Simply put the cursor on the variable or expression you want to add to the watch list and click the Quick Watch button.
Watch expressions can be edited using the Edit Watch option on the Debug menu.
Watch Expression Example:
1. Set a breakpoint at the X = X + 1 line in the example.
Programim object-oriented Faqa 266
2. Set a watch expression for the variable X. Run the application. Notice X appears in the watch window. Every time you re-start the application, the value of X changes.
3. At some point in the debug procedure, add a quick watch on Y. Notice it is now in the watch window.
4. Clear the breakpoint. Add a watch on the expression: X = Y. Set Watch Type to ‘Break When Value Is True.’ Run the application. Notice it goes into break mode and displays the watch window whenever X = Y. Delete this last watch expression.
Programim object-oriented Faqa 267
Call Stack:
Selecting the Call Stack button from the toolbar (or pressing Ctrl+L or selecting Call Stack from the View menu) will display all active procedures, that is those that have not been exited.
Call Stack helps you unravel situations with nested procedure calls to give you some idea of where you are in the application.
Call Stack Example:
1. Set a breakpoint on the Fcn = Cint() line in the general function procedure. Run the application. It will break at this line.
2. Press the Call Stack button. It will indicate you are currently in the Fcn procedure which was called from the Command1_Click procedure. Clear the breakpoint.
Single Stepping (Step Into):
While at a breakpoint, you may execute your program one line at a time by pressing <F8>, choosing the Step Into option in the Debug menu, or by clicking the Step Into button on the toolbar.
This process is single stepping. It allows you to watch how variables change (in the locals window) or how your form changes, one step at a time.
Programim object-oriented Faqa 268
You may step through several lines at a time by using Run To Cursor option. With this option, click on a line below your current point of execution. Then press Ctrl+<F8> (or choose Run To Cursor in the Debug menu). the program will run through every line up to the cursor location, then stop.
Step Into Example:
1. Set a breakpoint on the Do line in the example. Run the application.
2. When the program breaks, use the Step Into button to single step through the program.
3. At some point, put the cursor on the Loop While line. Try the Run To Cursor option (press Ctrl+<F8>).
Procedure Stepping (Step Over):
While single stepping your program, if you come to a procedure call you know functions properly, you can perform procedure stepping. This simply executes the entire procedure at once, rather than one step at a time.
To move through a procedure in this manner, press Shift+<F8>, choose Step Over from the Debug menu, or press the Step Over button on the toolbar.
Step Over Example:
1. Run the previous example. Single step through it a couple of times.
Programim object-oriented Faqa 269
2. One time through, when you are at the line calling the Fcn function, press the Step Over button. Notice how the program did not single step through the function as it did previously.
Function Exit (Step Out):
While stepping through your program, if you wish to complete the execution of a function you are in, without stepping through it line-by-line, choose the Step Out option. The function will be completed and you will be returned to the procedure accessing that function.
To perform this step out, press Ctrl+Shift+<F8>, choose Step Out from the Debug menu, or press the Step Out button on the toolbar. Try this on the previous example.
Programim object-oriented Faqa 270
Debugging Strategies
We’ve looked at each debugging tool briefly. Be aware this is a cursory introduction. Use the on-line help to delve into the details of each tool described. Only through lots of use and practice can you become a proficient debugger. There are some guidelines to doing a good job, though.
My first suggestion is: keep it simple. Many times, you only have one or two bad lines of code. And you, knowing your code best, can usually quickly narrow down the areas with bad lines. Don’t set up some elaborate debugging procedure if you haven’t tried a simple approach to find your error(s) first. Many times, just a few intelligently-placed Debug.Print statements or a few examinations of the immediate and locals windows can solve your problem.
A tried and true approach to debugging can be called Divide and Conquer. If you’re not sure where your error is, guess somewhere in the middle of your application code. Set a breakpoint there. If the error hasn’t shown up by then, you know it’s in the second half of your code. If it has shown up, it’s in the first half. Repeat this division process until you’ve narrowed your search.
And, of course, the best debugging strategy is to be careful when you first design and write your application to minimize searching for errors later.
Programim object-oriented Faqa 271
Sequential Files
In many applications, it is helpful to have the capability to read and write information to a disk file. This information could be some computed data or perhaps information loaded into a Visual Basic object.
Visual Basic supports two primary file formats: sequential and random access. We first look at sequential files.
A sequential file is a line-by-line list of data. You can view a sequential file with any text editor. When using sequential files, you must know the order in which information was written to the file to allow proper reading of the file.
Sequential files can handle both text data and variable values. Sequential access is best when dealing with files that have lines with mixed information of different lengths. I use them to transfer data between applications.
Sequential File Output (Variables)
We first look at writing values of variables to sequential files. The first step is to Open a file to write information to. The syntax for opening a sequential file for output is:
Open SeqFileName For Output As #N
where SeqFileName is the name of the file to open and N is an integer file number. The filename must be a complete path to the file.
When done writing to the file, Close it using:
Programim object-oriented Faqa 272
Close N
Once a file is closed, it is saved on the disk under the path and filename used to open the file.
Information is written to a sequential file one line at a time. Each line of output requires a separate Basic statement.
There are two ways to write variables to a sequential file. The first uses the Write statement:
Write #N, [variable list]
where the variable list has variable names delimited by commas. (If the variable list is omitted, a blank line is printed to the file.) This statement will write one line of information to the file, that line containing the variables specified in the variable list. The variables will be delimited by commas and any string variables will be enclosed in quotes. This is a good format for exporting files to other applications like Excel.
Example
Dim A As Integer, B As String, C As Single, D As Integer
.
.
Open TestOut For Output As #1
Write #1, A, B, C
Write #1, D
Close 1
Programim object-oriented Faqa 273
After this code runs, the file TestOut will have two lines. The first will have the variables A, B, and C, delimited by commas, with B (a string variable) in quotes. The second line will simply have the value of the variable D.
The second way to write variables to a sequential file is with the Print statement:
Print #N, [variable list]
This statement will write one line of information to the file, that line containing the variables specified in the variable list. (If the variable list is omitted, a blank line will be printed.) If the variables in the list are separated with semicolons (;), they are printed with a single space between them in the file. If separated by commas (,), they are spaced in wide columns. Be careful using the Print statement with string variables. The Print statement does not enclose string variables in quotes, hence, when you read such a variable back in, Visual Basic may have trouble knowing where a string ends and begins. It’s good practice to ‘tack on’ quotes to string variables when using Print.
Programim object-oriented Faqa 274
Example
Dim A As Integer, B As String, C As Single, D As Integer
.
.
Open TestOut For Output As #1
Print #1, A; Chr(34) + B + Chr(34), C
Print #1, D
Close 1
After this code runs, the file TestOut will have two lines. The first will have the variables A, B, and C, delimited by spaces. B will be enclosed by quotes [Chr(34)]. The second line will simply have the value of the variable D.
Quick Example: Writing Variables to Sequential Files
1. Start a new project.
2. Attach the following code to the Form_Load procedure. This code simply writes a few variables to sequential files.
Private Sub Form_Load()
Dim A As Integer, B As String, C As Single, D As Integer
A = 5
B = "Visual Basic"
Programim object-oriented Faqa 275
C = 2.15
D = -20
Open "Test1.Txt" For Output As #1
Open "Test2.Txt" For Output As #2
Write #1, A, B, C
Write #1, D
Print #2, A, B, C
Print #2, D
Close 1
Close 2
End Sub
3. Run the program. Use a text editor (try the Windows 95 Notepad) to examine the contents of the two files, Test1.Txt and Test2.Txt. They are probably in the Visual Basic main directory. Note the difference in the two files, especially how the variables are delimited and the fact that the string variable is not enclosed in quotes in Test2.Txt. Save the application, if you want to.
Programim object-oriented Faqa 276
Sequential File Input (Variables)
To read variables from a sequential file, we essentially reverse the write procedure. First, open the file using:
Open SeqFileName For Input As #N
where N is an integer file number and SeqFileName is a complete file path. The file is closed using:
Close N
The Input statement is used to read in variables from a sequential file. The format is:
Input #N, [variable list]
The variable names in the list are separated by commas. If no variables are listed, the current line in the file N is skipped.
Note variables must be read in exactly the same manner as they were written. So, using our previous example with the variables A, B, C, and D, the appropriate statements are:
Input #1, A, B, C
Input #1, D
These two lines read the variables A, B, and C from the first line in the file and D from the second line. It doesn’t matter whether the data was
Programim object-oriented Faqa 277
originally written to the file using Write or Print (i.e. commas are ignored).
Quick Example: Reading Variables from Sequential Files
1. Start a new project or simply modify the previous quick example.
2. Attach the following code to the Form_Load procedure. This code reads in files created in the last quick example.
Private Sub Form_Load()
Dim A As Integer, B As String, C As Single, D As Integer
Open "Test1.Txt" For Input As #1
Input #1, A, B, C
Debug.Print "A="; A
Debug.Print "B="; B
Debug.Print "C="; C
Input #1, D
Debug.Print "D="; D
Close 1
End Sub
Note the Debug.Print statements and how you can add some identifiers (in quotes) for printed information.
Programim object-oriented Faqa 278
3. Run the program. Look in the debug window and note the variable values. Save the application, if you want to.
4. Rerun the program using Test2.Txt as in the input file. What differences do you see? Do you see the problem with using Print and string variables? Because of this problem, I almost always use Write (instead of Print) for saving variable information to files. Edit the Test2.Txt file (in Notepad), putting quotes around the words Visual Basic. Rerun the program using this file as input - it should work fine now.
Writing and Reading Text Using Sequential Files
In many applications, we would like to be able to save text information and retrieve it for later reference. This information could be a text file created by an application or the contents of a Visual Basic text box.
Writing Text Files:
To write a sequential text file, we follow the simple procedure: open the file, write the file, close the file. If the file is a line-by-line text file, each line of the file is written to disk using a single Print statement:
Print #N, Line
where Line is the current line (a text string). This statement should be in a loop that encompasses all lines of the file. You must know the number of lines in your file, beforehand.
If we want to write the contents of the Text property of a text box named txtExample to a file, we use:
Programim object-oriented Faqa 279
Print #N, txtExample.Text
Example
We have a text box named txtExample. We want to save the contents of the Text property of that box in a file named MyText.ned on the c: drive in the \MyFiles directory. The code to do this is:
Open “c:\MyFiles\MyText.ned” For Output As #1
Print #1, txtExample.Text
Close 1
The text is now saved in the file for later retrieval.
Reading Text Files:
To read the contents of a previously-saved text file, we follow similar steps to the writing process: open the file, read the file, close the file. If the file is a text file, we read each individual line with the Line Input command:
Line Input #1, Line
Programim object-oriented Faqa 280
This line is usually placed in a Do/Loop structure that is repeated untill all lines of the file are read in. The EOF() function can be used to detect an end-of-file condition, if you don’t know, a prioiri, how many lines are in the file.
To place the contents of a file opened with number N into the Text property of a text box named txtExample we use the Input function:
txtExample.Text = Input(LOF(N), N)
This Input function has two arguments: LOF(N), the length of the file opened as N and N, the file number.
Example
We have a file named MyText.ned stored on the c: drive in the \MyFiles directory. We want to read that text file into the text property of a text box named txtExample. The code to do this is:
Open “c:\MyFiles\MyText.ned” For Input As #1
txtExample.Text = Input(LOF(1), 1)
Close 1
The text in the file will now be displayed in the text box.
Programim object-oriented Faqa 281
Random Access Files
Note that to access a particular data item in a sequential file, you need to read in all items in the file prior to the item of interest. This works acceptably well for small data files of unstructured data, but for large, structured files, this process is time-consuming and wasteful. Sometimes, we need to access data in nonsequential ways. Files which allow nonsequential access are random access files.
To allow nonsequential access to information, a random access file has a very definite structure. A random access file is made up of a number of records, each record having the same length (measured in bytes). Hence, by knowing the length of each record, we can easily determine (or the computer can) where each record begins. The first record in a random access file is Record 1, not 0 as used in Visual Basic arrays. Each record is usually a set of variables, of different types, describing some item. The structure of a random access file is:
Programim object-oriented Faqa 282
Record 1
N bytes
Record 2
N bytes
Record 3
N bytes
.
.
Record Last
N bytes
A good analogy to illustrate the differences between sequential files and random access files are cassette music tapes and compact discs. To hear a song on a tape (a sequential device), you must go past all songs prior to your selection. To hear a song on a CD (a random access device), you simply go directly to the desired selection. One difference here though is we require all of our random access records to be the same length - not a good choice on CD’s!
To write and read random access files, we must know the record length in bytes. Some variable types and their length in bytes are:
Type Length (Bytes)
Integer 2
Long 4
Single 4
Double 8
String 1 byte per character
So, for every variable that is in a file’s record, we need to add up the individual variable length’s to obtain the total record length. To ease this task, we introduce the idea of user-defined variables.
User-Defined Variables
Data used with random access files is most often stored in user-defined variables. These data types group variables of different types into one assembly with a single, user-defined type associated with the group. Such types significantly simplify the use of random access files.
Programim object-oriented Faqa 283
The Visual Basic keyword Type signals the beginning of a user-defined type declaration and the words End Type signal the end. An example best illustrates establishing a user-defined variable. Say we want to use a variable that describes people by their name, their city, their height, and their weight. We would define a variable of Type Person as follows:
Type Person
Name As String
City As String
Height As Integer
Weight As Integer
End Type
These variable declarations go in the same code areas as normal variable declarations, depending on desired scope. At this point, we have not reserved any storage for the data. We have simply described to Visual Basic the layout of the data.
To create variables with this newly defined type, we employ the usual Dim statement. For our Person example, we would use:
Dim Lou As Person
Dim John As Person
Dim Mary As Person
And now, we have three variables, each containing all the components of the variable type Person. To refer to a single component within a user-defined type, we use the dot-notation:
VarName.Component
Programim object-oriented Faqa 284
As an example, to obtain Lou’s Age, we use:
Dim AgeValue as Integer
.
.
AgeValue = Lou.Age
Note the similarity to dot-notation we’ve been using to set properties of various Visual Basic tools.
Writing and Reading Random Access Files
We look at writing and reading random access files using a user-defined variable. For other variable types, refer to Visual Basic on-line help. To open a random access file named RanFileName, use:
Open RanFileName For Random As #N Len = RecordLength
where N is an available file number and RecordLength is the length of each record. Note you don’t have to specify an input or output mode. With random access files, as long as they’re open, you can write or read to them.
To close a random access file, use:
Close N
As mentioned previously, the record length is the sum of the lengths of all variables that make up a record. A problem arises with String type
Programim object-oriented Faqa 285
variables. You don’t know their lengths ahead of time. To solve this problem, Visual Basic lets you declare fixed lengths for strings. This allows you to determine record length. If we have a string variable named StrExample we want to limit to 14 characters, we use the declaration:
Dim StrExample As String * 14
Recall each character in a string uses 1 byte, so the length of such a variable is 14 bytes.
Recall our example user-defined variable type, Person. Let’s revisit it, now with restricted string lengths:
Type Person
Name As String * 40
City As String * 35
Height As Integer
Weight As Integer
End Type
The record length for this variable type is 79 bytes (40 + 35 +2 + 2). To open a file named PersonData as File #1, with such records, we would use the statement:
Open PersonData For Random As #1 Len = 79
The Get and Put statements are used to read from and write to random access files, respectively. These statements read or write one record at a time. The syntax for these statements is simple:
Programim object-oriented Faqa 286
Get #N, [RecordNumber], variable
Put #N, [RecordNumber], variable
The Get statement reads from the file and stores data in the variable, whereas the Put statement writes the contents of the specified variable to the file. In each case, you can optionally specifiy the record number. If you do not specify a record number, the next sequential position is used.
The variable argument in the Get and Put statements is usually a single user-defined variable. Once read in, you obtain the component parts of this variable using dot-notation. Prior to writing a user-defined variable to a random access file, you ‘load’ the component parts using the same dot-notation.
There’s a lot more to using random access files; we’ve only looked at the basics. Refer to your Visual Basic documentation and on-line help for further information. In particular, you need to do a little cute programming when deleting records from a random access file or when ‘resorting’ records.
Programim object-oriented Faqa 287
Using the Open and Save Common Dialog Boxes
Note to both write and read sequential and random access files, we need a file name for the Open statement. To ensure accuracy and completeness, it is suggested that common dialog boxes (briefly studied in Class 4) be used to get this file name information from the user. I’ll provide you with a couple of code segments that do just that. Both segments assume you have a common dialog box on your form named cdlFiles, with the CancelError property set equal to True. With this property True, an error is generated by Visual Basic when the user presses the Cancel button in the dialog box. By trapping this error, it allows an elegant exit from the dialog box when canceling the operation is desired.
The code segment to obtain a file name (MyFileName with default extension Ext) for opening a file to read is:
Dim MyFileName As String, Ext As String
.
.
cdlFiles.Filter = "Files (*." + Ext + ")|*." + Ext
cdlFiles.DefaultExt = Ext
cdlFiles.DialogTitle = "Open File"
cdlFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist
On Error GoTo No_Open
cdlFiles.ShowOpen
MyFileName = cdlFiles.filename
.
.
Exit Sub
No_Open:
Programim object-oriented Faqa 288
Resume ExitLIne
ExitLine:
Exit Sub
End Sub
A few words on what’s going on here. First, some properties are set such that only files with Ext (a three letter string variable) extensions are displayed (Filter property), the default extension is Ext (DefaultExt property), the title bar is set (DialogTitle property), and some Flags are set to insure the file and path exist (see Appendix II for more common dialog flags). Error trapping is enabled to trap the Cancel button. Finally, the common dialog box is displayed and the filename property returns with the desired name. That name is put in the string variable MyFileName. What you do after obtaining the file name depends on what type of file you are dealing with. For sequential files, you would open the file, read in the information, and close the file. For random access files, we just open the file here. Reading and writing to/from the file would be handled elsewhere in your coding.
The code segment to retrieve a file name (MyFileName) for writing a file is:
Dim MyFileName As String, Ext As String
.
.
cdlFiles.Filter = "Files (*." + Ext + ")|*." + Ext
cdlFiles.DefaultExt = Ext
cdlFiles.DialogTitle = "Save File"
cdlFiles.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist
On Error GoTo No_Save
Programim object-oriented Faqa 289
cdlFiles.ShowSave
MyFileName = cdlFiles.filename
.
.
Exit Sub
No_Save:
Resume ExitLine
ExitLine:
Exit Sub
End Sub
Note this code is essentially the same used for an Open file name. The Flags property differs slightly. The user is prompted if a previously saved file is selected for overwrite. After obtaining a valid file name for a sequential file, we would open the file for output, write the file, and close it. For a random access file, things are trickier. If we want to save the file with the same name we opened it with, we simply close the file. If the name is different, we must open a file (using a different number) with the new name, write the complete random access file, then close it. Like I said, it’s trickier.
We use both of these code segments in the final example where we write and read sequential files.
Programim object-oriented Faqa 290
Example 6-3
Note Editor - Reading and Saving Text Files
1. We now add the capability to read in and save the contents of the text box in the Note Editor application from last class. Load that application. Add a common dialog box to your form. Name it cdlFiles and set the CancelError property to True.
2. Modify the File menu (use the Menu Editor and the Insert button) in your application, such that Open and Save options are included. The File menu should now read:
File
New
Open
Save
Exit
Properties for these new menu items should be:
Caption Name Shortcut
&Open mnuFileOpen [None]
&Save mnuFileSave [None]
3. The two new menu options need code. Attach this code to the mnuFileOpen_Click event. This uses a modified version of the code segment seen previously. We assign the extension ned to our note editor files.
Programim object-oriented Faqa 291
Private Sub mnuFileOpen_Click()
cdlFiles.Filter = "Files (*.ned)|*.ned"
cdlFiles.DefaultExt = "ned"
cdlFiles.DialogTitle = "Open File"
cdlFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist
On Error GoTo No_Open
cdlFiles.ShowOpen
Open cdlFiles.filename For Input As #1
txtEdit.Text = Input(LOF(1), 1)
Close 1
Exit Sub
No_Open:
Resume ExitLine
ExitLine:
Exit Sub
End Sub
And for the mnuFileSave_Click procedure, use this code. Much of this can be copied from the previous procedure.
Private Sub mnuFileSave_Click()
cdlFiles.Filter = "Files (*.ned)|*.ned"
cdlFiles.DefaultExt = "ned"
cdlFiles.DialogTitle = "Save File"
cdlFiles.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist
Programim object-oriented Faqa 292
On Error GoTo No_Save
cdlFiles.ShowSave
Open cdlFiles.filename For Output As #1
Print #1, txtEdit.Text
Close 1
Exit Sub
No_Save:
Resume ExitLine
ExitLine:
Exit Sub
End Sub
Each of these procedures is similar. The dialog box is opened and, if a filename is returned, the file is read/written. If Cancel is pressed, no action is taken. These routines can be used as templates for file operations in other applications.
4. Save your application. Run it and test the Open and Save functions. Note you have to save a file before you can open one. Check for proper operation of the Cancel button in the common dialog box.
5. If you have the time, there is one major improvement that should be made to this application. Notice that, as written, only the text information is saved, not the formatting (bold, italic, underline, size). Whenever a file is opened, the text is displayed based on current settings. It would be nice to save formatting information along with the text. This can be done, but it involves a fair amount of reprogramming. Suggested steps:
A. Add lines to the mnuFileSave_Click routine that write the text box properties FontBold, FontItalic, FontUnderline, and FontSize to a separate sequential file. If your text file is named TxtFile.ned, I would suggest naming the formatting file
Programim object-oriented Faqa 293
TxtFile.fmt. Use string functions to put this name together. That is, chop the ned extension off the text file name and tack on the fmt extension. You’ll need the Len() and Left() functions.
B. Add lines to the mnuFileOpen_Click routine that read the text box properties FontBold, FontItalic, FontUnderline, and FontSize from your format sequential file. You’ll need to define some intermediate variables here because Visual Basic won’t allow you to read properties directly from a file. You’ll also need logic to set/reset any check marks in the menu structure to correspond to these input properties.
C. Add lines to the mnuFileNew_Click procedure that, when the user wants a new file, reset the text box properties FontBold, FontItalic, FontUnderline, and FontSize to their default values and set/reset the corresponding menu check marks.
D. Try out the modified application. Make sure every new option works as it should.
Actually, there are ‘custom’ tools (we’ll look at custom tools in Class 10) that do what we are trying to do with this modification, that is save text box contents with formatting information. Such files are called ‘rich text files’ or rtf files. You may have seen these before when transferring files from one word processor to another.
Programim object-oriented Faqa 294
6. Another thing you could try: Modify the message box that appears when you try to Exit. Make it ask if you wish to save your file before exiting - provide Yes, No, Cancel buttons. Program the code corresponding to each possible response. Use calls to existing procedures, if possible.
Exercise 6-1
Information Tracking
Design and develop an application that allows the user to enter (on a daily basis) some piece of information that is to be saved for future review and reference. Examples could be stock price, weight, or high temperature for the day. The input screen should display the current date and an input box for the desired information. all values should be saved on disk for future retrieval and update. A scroll bar should be available for reviewing all previously-stored values.
My Solution:
Form:
Programim object-oriented Faqa 295
Properties:
Form frmWeight:
BorderStyle = 1 - Fixed Single
Caption = Weight Program
VScrollBar vsbControl:
Min = 1
Value = 1
TextBox txtWeight:
Alignment = 2 - Center
FontName = MS Sans Serif
FontSize = 13.5
Label lblFile:
BackColor = &H0000FFFF& (White)
BorderStyle = 1 - Fixed Single
Caption = New File
FontName = MS Sans Serif
FontBold = True
FontItalic = True
FontSize = 8.25
Label lblDate:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
Programim object-oriented Faqa 296
FontSize = 13.5
Label Label2:
Alignment = 2 - Center
Caption = Weight
FontName = MS Sans Serif
FontSize = 13.5
FontBold = True
Label Label1:
Alignment = 2 - Center
Caption = Date
FontName = MS Sans Serif
FontSize = 13.5
FontBold = True
CommonDialog cdlFiles:
CancelError = True
Menu mnuFile:
Caption = &File
Menu mnuFileNew:
Caption = &New
Programim object-oriented Faqa 297
Menu mnuFileOpen:
Caption = &Open
Menu mnuFileSave:
Caption = &Save
Menu mnuLine:
Caption = -
Menu mnuFileExit:
Caption = E&xit
Code:
General Declarations:
Option Explicit
Dim Dates(1000) As Date
Dim Weights(1000) As String
Dim NumWts As Integer
Init General Procedure:
Sub Init()
NumWts = 1: vsbControl.Value = 1: vsbControl.Max = 1
Dates(1) = Format(Now, "mm/dd/yy")
Weights(1) = ""
lblDate.Caption = Dates(1)
txtWeight.Text = Weights(1)
lblFile.Caption = "New File"
Programim object-oriented Faqa 298
End Sub
Form Load Event:
Private Sub Form_Load()
frmWeight.Show
Call Init
End Sub
mnufileExit Click Event:
Private Sub mnuFileExit_Click()
'Make sure user really wants to exit
Dim Response As Integer
Response = MsgBox("Are you sure you want to exit the weight program?", vbYesNo + vbCritical + vbDefaultButton2, "Exit Editor")
If Response = vbNo Then
Exit Sub
Else
End
End If
End Sub
mnuFileNew Click Event:
Programim object-oriented Faqa 299
Private Sub mnuFileNew_Click()
'User wants new file
Dim Response As Integer
Response = MsgBox("Are you sure you want to start a new file?", vbYesNo + vbQuestion, "New File")
If Response = vbNo Then
Exit Sub
Else
Call Init
End If
End Sub
mnuFileOpen Click Event:
Private Sub mnuFileOpen_Click()
Dim I As Integer
Dim Today As Date
Dim Response As Integer
Response = MsgBox("Are you sure you want to open a new file?", vbYesNo + vbQuestion, "New File")
If Response = vbNo Then Exit Sub
cdlFiles.Filter = "Files (*.wgt)|*.wgt"
cdlFiles.DefaultExt = "wgt"
cdlFiles.DialogTitle = "Open File"
cdlFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist
On Error GoTo No_Open
Programim object-oriented Faqa 300
cdlFiles.ShowOpen
Open cdlFiles.filename For Input As #1
lblFile.Caption = cdlFiles.filename
Input #1, NumWts
For I = 1 To NumWts
Input #1, Dates(I), Weights(I)
Next I
Close 1
Today = Format(Now, "mm/dd/yy")
If Today <> Dates(NumWts) Then
NumWts = NumWts + 1
Dates(NumWts) = Today
Weights(NumWts) = ""
End If
vsbControl.Max = NumWts
vsbControl.Value = NumWts
lblDate.Caption = Dates(NumWts)
txtWeight.Text = Weights(NumWts)
Exit Sub
No_Open:
Resume ExitLine
ExitLine:
Exit Sub
End Sub
Programim object-oriented Faqa 301
mnuFileSave Click Event:
Private Sub mnuFileSave_Click()
Dim I As Integer
cdlFiles.Filter = "Files (*.wgt)|*.wgt"
cdlFiles.DefaultExt = "wgt"
cdlFiles.DialogTitle = "Save File"
cdlFiles.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist
On Error GoTo No_Save
cdlFiles.ShowSave
Open cdlFiles.filename For Output As #1
lblFile.Caption = cdlFiles.filename
Write #1, NumWts
For I = 1 To NumWts
Write #1, Dates(I), Weights(I)
Next I
Close 1
Exit Sub
No_Save:
Resume ExitLine
ExitLine:
Exit Sub
End Sub
txtWeight Change Event:
Programim object-oriented Faqa 302
Private Sub txtWeight_Change()
Weights(vsbControl.Value) = txtWeight.Text
End Sub
txtWeight KeyPress Event:
Private Sub txtWeight_KeyPress(KeyAscii As Integer)
If KeyAscii >= vbKey0 And KeyAscii <= vbKey9 Then
Exit Sub
Else
KeyAscii = 0
End If
End Sub
vsbControl Change Event:
Private Sub vsbControl_Change()
lblDate.Caption = Dates(vsbControl.Value)
txtWeight.Text = Weights(vsbControl.Value)
txtWeight.SetFocus
End Sub
Exercise 6-2
‘Recent Files’ Menu Option
Programim object-oriented Faqa 303
Under the File menu on nearly every application (that opens files) is a list of the four most recently-used files (usually right above the Exit option). Modify your information tracker to implement such a feature. This is not trivial -- there are lots of things to consider. For example, you’ll need a file to store the last four file names. You need to open that file and initialize the corresponding menu entries when you run the application -- you need to rewrite that file when you exit the application. You need logic to re-order file names when a new file is opened or saved. You need logic to establish new menu items as new files are used. You’ll need additional error-trapping in the open procedure, in case a file selected from the menu no longer exists. Like I said, a lot to consider here.
My Solution:
These new menu items immediately precede the existing Exit menu item:
Menu mnuFileRecent:
Caption = [Blank]
Index = 0, 1, 2, 3 (a control array)
Visible = False
Menu mnuFileBar:
Caption = -
Visible = False
Code Modifications (new code is bold and italicized):
General Declarations:
Option Explicit
Programim object-oriented Faqa 304
Dim Dates(1000) As Date
Dim Weights(1000) As String
Dim NumWts As Integer
Dim NFiles As Integer, RFile(3) As String, MenuOpen As Integer, FNmenu As String
Rfile Update General Procedure:
Sub RFile_Update(NewFile As String)
‘Routine to place newest file name in proper order
‘in menu structure
Dim I As Integer, J As Integer, InList As Integer
'Convert name to all upper case letters
NewFile = UCase(NewFile)
'See if file is already in list
InList = 0
For I = 0 To NFiles - 1
If RFile(I) = NewFile Then InList = 1: Exit For
Next I
'If file not in list, increment number of items with
'a maximum of 4. Then, move others down, then place
'new name at top of list
If InList = 0 Then
NFiles = NFiles + 1
If NFiles > 4 Then
NFiles = 4
Programim object-oriented Faqa 305
Else
If NFiles = 1 Then mnuFileBar.Visible = True
mnuFileRecent(NFiles - 1).Visible = True
End If
If NFiles <> 1 Then
For I = NFiles - 1 To 1 Step -1
RFile(I) = RFile(I - 1)
Next I
End If
RFile(0) = NewFile
Else
'If file already in list, put name at top and shift
'others accordingly
If I <> 0 Then
For J = I - 1 To 0 Step -1
RFile(J + 1) = RFile(J)
Next J
RFile(0) = NewFile
End If
End If
'Set menu captions according to new list
For I = 0 To NFiles - 1
mnuFileRecent(I).Caption = "&" + Format(I + 1, "# ") + RFile(I)
Next I
End Sub
Programim object-oriented Faqa 306
Form Load Event:
Private Sub Form_Load()
Dim I As Integer
'Open .ini file and load in recent file names
Open "weight.ini" For Input As #1
NFiles = 0: MenuOpen = 0
For I = 0 To 3
Input #1, RFile(I)
If RFile(I) <> "" Then
NFiles = NFiles + 1
mnuFileBar.Visible = True
mnuFileRecent(I).Caption = "&" + Format(I + 1, "# ") + RFile(I)
mnuFileRecent(I).Visible = True
End If
Next I
Close 1
frmWeight.Show
Call Init
End Sub
mnuFileExit Click Event:
Private Sub mnuFileExit_Click()
'Make sure user really wants to exit
Programim object-oriented Faqa 307
Dim Response As Integer, I As Integer
Response = MsgBox("Are you sure you want to exit the weight program?", vbYesNo + vbCritical + vbDefaultButton2, "Exit Editor")
If Response = vbNo Then
Exit Sub
Else
'Write out .ini file when done
Open "weight.ini" For Output As #1
For I = 0 To 3
Write #1, RFile(I)
Next I
Close 1
End
End If
End Sub
Programim object-oriented Faqa 308
mnuFileOpen Click Event:
Private Sub mnuFileOpen_Click()
Dim I As Integer
Dim Today As Date
Dim Response As Integer
Dim File_To_Open As String
Response = MsgBox("Are you sure you want to open a new file?", vbYesNo + vbQuestion, "New File")
If Response = vbNo Then Exit Sub
If MenuOpen = 0 Then
cdlFiles.Filter = "Files (*.wgt)|*.wgt"
cdlFiles.DefaultExt = "wgt"
cdlFiles.DialogTitle = "Open File"
cdlFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist
On Error GoTo No_Open
cdlFiles.ShowOpen
File_To_Open = cdlFiles.filename
Else
File_To_Open = FNmenu
End If
MenuOpen = 0
On Error GoTo BadOpen
Open File_To_Open For Input As #1
lblFile.Caption = File_To_Open
Input #1, NumWts
Programim object-oriented Faqa 309
For I = 1 To NumWts
Input #1, Dates(I), Weights(I)
Next I
Close 1
Call RFile_Update(File_To_Open)
Today = Format(Now, "mm/dd/yy")
If Today <> Dates(NumWts) Then
NumWts = NumWts + 1
Dates(NumWts) = Today
Weights(NumWts) = ""
End If
vsbControl.Max = NumWts
vsbControl.Value = NumWts
lblDate.Caption = Dates(NumWts)
txtWeight.Text = Weights(NumWts)
Exit Sub
No_Open:
Resume ExitLine
ExitLine:
Exit Sub
Programim object-oriented Faqa 310
BadOpen:
Select Case MsgBox(Error(Err.Number), vbCritical + vbRetryCancel, "File Open Error")
Case vbRetry
Resume
Case vbCancel
Resume No_Open
End Select
End Sub
mnuFileRecent Click Event:
Private Sub mnuFileRecent_Click(Index As Integer)
FNmenu = RFile(Index): MenuOpen = 1
Call mnuFileOpen_Click
End Sub
mnuFileSave Click Event:
Private Sub mnuFileSave_Click()
Dim I As Integer
cdlFiles.Filter = "Files (*.wgt)|*.wgt"
cdlFiles.DefaultExt = "wgt"
cdlFiles.DialogTitle = "Save File"
cdlFiles.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist
On Error GoTo No_Save
Programim object-oriented Faqa 311
cdlFiles.ShowSave
Open cdlFiles.filename For Output As #1
lblFile.Caption = cdlFiles.filename
Write #1, NumWts
For I = 1 To NumWts
Write #1, Dates(I), Weights(I)
Next I
Close 1
Call RFile_Update(cdlFiles.filename)
Exit Sub
No_Save:
Resume ExitLine
ExitLine:
Exit Sub
End Sub
Programim object-oriented Faqa 312
8. Aksesimi dhe Menaxhimi i
Bazave te te Dhenave
Deri tani, kemi pare fuqine e mjeteve te Visual Basic ne ndertimin e
aplikacionit. Ne kete leksion, do te shikojme nje nga veglat me te fuqishme,
Data Control. Duke perdorur kete vegel, ne kombinim me vegla te tjera, na
lejohet te aksesojme dhe menaxhojme baza te dhenash.
Nje ndryshim shume i madhe ne Visual Basic, me perdorimin e Versionit 6.0,
eshte perdorimi i veglave per menaxhimin e bazave te te dhenave. U
zhvilluan veglat e reja bazuar ne teknologjine ActiveX Data Object (ADO).
Keto vegla te reja zevendesuan menjehere veglat e vjetra te quajtura DAO
(Data Access Object). Ne do te diskutojme vetem veglat ADO. Microsoft
ende i perfshin veglat DAO per efekt kompatibiliteti.
Programim object-oriented Faqa 313
Struktura dhe terminologjia e bazave te te dhenave
Me fjale te thjeshta, nje baze te dhenash eshte nje koleksion informatash.
Ky koleksion ngarkohet ne tabela apo matrica.
Rreshtat ne nje tabele te bazes se te dhenave perdoren per te pershkruar
elemente te njejta. Rreshtave te nje tabele bazash te dhenash u referohemi
si rekorde (regjistrime). Ne pergjithesi, nuk ka dy rreshta te njejte ne nje
tabele.
Kollonat ne nje tabele te bazes se te dhenave paraqesin karakteristikat e
regjistrimeve. Keto karakteristika quhen fusha te bazes se te dhenave. Cdo
fushe permban nje informacion specifik. Ne percaktimin e fushave te bazes
se te dhenave, ju specifikoni tipin e te dhenes, i caktoni nje gjatesi dhe
percaktoni atribute (karakteristika) te tjera.
Me poshte eshte dhene shembulli i nje baze te dhenash:
Programim object-oriented Faqa 314
Ne kete tabele, secili regjistrim paraqet nje individ te vetem. Fushat
perfshijne: numrin e identifikimit (ID No), Emrin, Datelindjen, Gjatesine dhe
Peshen.
Pjesa me e madhe e bazes se te dhenave perdor indekset (indexes) per te
lejuar aksesim te shpejte te informacioneve. Indexet jane lista te renditura
qe shenojne ne nje rresht te vecante ne tabele. Ne shembullin qe pame me
siper, fusha ID No mund te perdoret si index.
Nje baze te dhenash qe perdor vetem nje tabele, quhet flat database.
Shumica e bazave te te dhenave ndertohet nga shume tabela. Kur perdoren
shume tabela brenda nje baze te dhenash, keto tabela mund te kene disa
fusha te perbashketa per te lejuar kryqezimin midis tabelave. Referimi i nje
tabele nga nje tjeter quhet lidhje (relation). Disa grupime tabelash quhen
relational databases.
Ne shembullin tone te pare, do te perdorim nje baze te thjeshte te dhenash,
qe vjen me Visual Basic. Kjo baze te dhenash (BIBLIO.MDB) gjendet ne
dosjen kryesore te Visual Basic (provoni c:\Program Files\Microsoft Visual
Studio\VB98). Eshte nje baze te dhenash per librat rreth kompjuterit. Le te
shohim strukturen e lidhjeve te saj. Database BIBLIO.MDB perbehet nga 4
tabela:
Programim object-oriented Faqa 315
Programim object-oriented Faqa 316
Tabela Autoret konsiston ne numrin identifikues te autoreve, emrit te
autorit dhe vitin e lindjes. Tabela Botuesit ka informacione qe i perkasin
botuesve te librave. Disa nga fushat qe perfshihen jane numri i identifikimit,
emri i botuesit dhe numra telefoni. Tabela Title Author shoqeron nje
ISBN libri (number universal qe i shoqerohet nje libri) me nje numer
identifikimi autori. Tabela Titujt ka disa fusha qe pershkruajne cdo liber
individual, duke perfshire titullin, ISBN dhe informacione mbi botuesin.
Shenim: Cdo tabele ka dy lloj informacionesh: source data dhe
relational data. Source data jane te dhena reale, sic jane titujt apo
emrat e autoreve. Relational data jane referencat e te dhenave ne tabelat
e tjera, sic jane Au_ID dhe PubID. Ne tabelat Autoret, Botuesit dhe Title
Author, kollona e pare edhte perdorur si index. Ne tabelen Titujt, vlera
e ISBN eshte index.
Duke perdorur lidhjen e te dhenave ne 4 tabelat, ne mund te jemi ne gjendje
te marrim nje pershkrim te plote per ndonje titull libri ne bazen e te dhenave.
Le te shohim shembullin:
Ketu, libri me titullin “Step-by-step dBase IV,” ne tabelen Titujt, ka ISBN 0-
0280095-2-5 dhe PubID = 52. Duke marre PubID ne tabelen Botuesit,
Programim object-oriented Faqa 317
shohim qe libri eshte botuar nga McGraw-Hill dhe gjithashtu na lejon te
aksesojme te gjitha informacionet e tjera qe i perkasin ketij botuesi.
Perdorimi i ISBN ne tabelen Title Author na siguron numrin e identifikimit
te autorit (Au_ID) 171, e cila perdorur ne tabelen Autoret , na tregon qe
autori i librit eshte Toby Wraye.
Ne mund te krijojme tabela nga tabelat ekzistuese ne bazen e te dhenave.
Keto tabela virtuale apo pamje llogjike, behen duke perdorur queries
_te e bazes se te dhenave. Nje query eshte thjesht nje kerkese per
informacion nga tabelat e database. Si shembull ne bazen e te dhenave
BIBLIO.MDB, duke perdorur gjuhen e query_ve, ne mund ti ‘kerkojme’ bazes
se te dhenave te formoje nje tabele me te gjithe autoret dhe librat e
publikuar mbas 1992, ose me te gjithe autoret te cileve u fillon emri me B.
Gjurmimi i te gjithe informacioneve ne nje baze te dhenash behet nga
database management system (DBMS). Ato perdoren per te krijuar dhe
mirembajtur bazat e te dhenave. Shembuj te programeve komerciale DBMS
jane Microsoft Access, Microsoft FoxPro, Borland Paradox, Borland dBase,
Claris FileMaker etj. Gjithashtu ju mund te perdorni Visual Basic per te
zhvilluar nje DBMS. Visual Basic ndan te njejtet ‘motorre (engine)’ te
perdorur nga Microsoft Access, te njohur si Jet engine. Ne kete rast, ne do
te shohim se si te perdorim Visual Basic per te aksesuar te dhenat, te
shfaqim te dhenat dhe te ekzekutojme disa operacione elementare
menaxhimi.
Programim object-oriented Faqa 318
ADO Data Control
ADO (ActiveX Data Object) data control eshte nderfaqesi primar dhe me i
rendesishem ndermjet nje aplikacioni ne Visual Basic dhe nje baze te
dhenash. Ai mund te perdoret pa shkruajtur ndonje rresht kodi!!!! Ose, ai
mund te jete nje pjese qendrore e nje baze te dhenash komplekse
menaxhimi sistemi. Kjo ikone mund te mos shfaqet ne toolbox e Visual
Basic. Nqs nuk shfaqet, zgjidhni Project nga menuja kryesore, dhe me tej
klikoni Components. Do ju shfaqet dritarja Components. Zgjidhni
Microsoft ADO Data Control, me pas OK. Kontrolli do te shtohet ne
toolbox.
Sic eshte permendur ne Perseritje, versionet e meparshme te Visual Basic
kane perdorur tjeter data control. Ky kontroll eshte akoma i perfshire ne
Visual Basic 6.0 (per efekte kompatibiliteti) dhe ka si ikone te saj:
Sigurohuni qe nuk jeni duke perdorur kete data control per praktiken dhe
ushtrimet qe do bejme gjate ketij cikli leksionesh. Ky kontroll eshte i
Programim object-oriented Faqa 319
pershtatshem per baza te vogla te dhenash. Nese doni mund ta studioni ne
menyre te pavarur.
Data control mund te perdoret per te realizuar detyrat me poshte:
1. Lidhjen me nje database.
2. Hapjen e nje tabele specifike.
3. Krijimin e nje tabele virtuale bazuar ne nje query.
4. Kalimin e fushave te database_es ne tools_et e Visual Basic,
per shfaqje apo modifikim.
5. Shtimin e regjistrimeve ne database apo modifikimin e tyre.
6. Gjurmimin e ndonje gabimi qe mund te ndodhi gjate aksesimit
te te dhenave.
7. Mbylljen e database.
Data Control Properties
Align Percakton se ku shfaqet data control.
Caption Fraza qe do te shfaqet ne data control.
ConnectionString Permban informacionin qe perdoret
per te krijuar lidhjen me nje database.
LockType Tregon tipin e kycjes (nivele sigurie)
vendosur ne regjistrime (record) gjate
editimit (default setting e bejne
databasen read-only).
Recordset Nje grup regjistrimesh percaktuar nga nje
data control’s ConnectionString dhe
Programim object-oriented Faqa 320
RecordSource properties. Eshte vetem
Run-time.
RecordSource Percaktojne tabelen (ose tabelen
virtuale) te ciles i bashkangjitet data
control.
Si rregull, ju nevojitet nje data control per cdo tabele te database, ose tabele
virtuale qe do te aksesoni. Nje rresht i tabeles eshte i aksesueshem nga cdo
data control ne cdo moment. Kjo na tregon ne regjistrimin korent.
Kur nje data control eshte vendosur ne nje form, shfaqen ne te 4 butona me
shigjeta me emertime si me poshte:
Keto shigjeta perdoren per te levizur neper regjistrime (rreshtat e tabeles).
Sic u tregua, butonat mund te perdoren per te vajtur ne fillim te tabeles, ne
fund te tabeles apo nga regjistrimi ne regjistrim.
Data Links
Pasi keni vendosur nje data control ne form, duhet te percaktoni vetine
ConnectionString. ADO data control mund te lidhet me tipe te ndryshme
bazash te dhena. Ka tre menyra per tu lidhur me nje baze te dhenash:
1. Duke perdorur nje data link,
Programim object-oriented Faqa 321
2. Duke perdorur nje ODBC data source,
3. Ose duke perdorur connection string.
Ne kete leksion, ne do te shikojme vetem lidhjen me baze te dhenash
ndertuar ne Microsoft Access duke perdorur data link. Nje data link eshte
nje skedar me prapashtese UDL I cili permban informacione per tipin e bazes
se te dhenave.
Nqs baza juaj e te dhenave nuk ka nje data link, ath ju duhet ta krijoni ate.
Le ta ilustrojme kete process me nje shembull. Ne shembullin tone te pare do
te bazen e te dhenave BIBLIO.MDB. Hapat me poshte tregojne se si mund te
krijohet data link per kete baze te dhenash:
1. Hapni Windows Explorer.
2. Hapni dosjen ku do te ngarkoni (ruani) skedarin e data link_ut qe do
krijoni.
3. Nqs jeni duke punuar me Windows 2000 ose versione te mevonshme
te sistemit operativ zgjidhni komanden New te menuse File dhe nga
lista e skedareve zgjidhni Text Document. Ne dosjen active shtohet
nje skedar me emrin New Text Document.txt. Riemertoni kete
skedar me ermin qe doni duke ndryshuar edhe prapashtesen ne .udl
(ne rastin tone BIBLIO.UDL).
Shenim Lajmerimin per shkaqet qe sjell ndryshimi I prapashteses
injorojeni duke klikuar Yes.
Nqs jeni duke punuar me sistemin operativ Windows 98 dhe Windows
NT me Microsoft Data Access Components (MDAC) te instaluar, klikoni
me butonin e djathte te mous_it ne zonen e djathte te Windows
Explorer, dhe zgjidhni New. Nga lista e skedareve, zgjidhni Microsoft
Data Link. Ne dosjen active shtohet nje skedar me emrin New
Programim object-oriented Faqa 322
Microsoft Data Link.udl. Riemertoni skedarin e ri te krijuar
BIBLIO.UDL
4. Klikoni me butonin e djathte te mous_it mbi skedarin e ri UDL dhe
zgjidhni Properties.
5. Zgjidhni tab_in Provider dhe me tej Microsoft Jet 3.51 OLE DB
Provider (baze te dhenash ne Access).
6. Klikoni butonine Next per te vajtur ne tab_in Connection.
7. Klikoni ne butonin e treguar nga shigjeta
dhe zgjidhni skedarin BIBLIO.MDB I cili ndodhet ne dosjen kryesore te
Visual Basic (..\Program Files\Microsoft Visual Studio\VB98\
BIBLIO.MDB).
8. Klikoni Test Connection. Nqs testimi ka rezultuar me sukses, klikoni
click OK. Skedari UDL tashme eshte krijuar dhe duke perdorur hapat
me poshte mund ti ngarkohet ConnectionString.
Nqs keni krijuar data link, klikoni ne vetine ConnectionString dhe zgjidhni
Use Data Link File. Me pas klikoni butonin Browsedhe gjeni aty skedarin.
Klikoni Open. Tashme data link eshte ngarkuar ne vitine. Klikoni OK.
Programim object-oriented Faqa 323
Percaktimi i tabelave
Sapo ADO data control eshte e lidhur me bazen e te dhenave, duhet te
percaktojme nje tabele me kete kontroll. Thirrja e cdo data control eshte e
bashkangjitur me nje tabele te vetme, qofte ajo nje tabele e ekzistuese apo
tabele virtuale e bazes se te dhenave. Percaktimi i nje tabele behet ndermjet
vetise RecordSource.
Tabelat percaktohen duke krijuar queries ne bazen e te dhenave. Gjuha qe
perdoret per krijimin e query_ve eshte SQL (shqiptohet 'sequel', structured
query language). Gjuha SQL ne pamje te pare ngjan me gjuhen angleze dhe
perdoret ne pjesen me te madhe te bazave te te dhenave. Mund te
perdorim SQL per te formuluar nje pyetje e cila i drejtohet me tej bazes se te
dhenave. Baza e te dhenave i pergjigjet kesaj pyetje me nje tabele te re e
cila permban tabelat dhe fushat qe perbushin kriterin.
Nje tabele percaktohet duke vendosur ne vetine RecordSource te data
control nje shprehje te vlefshme SQL. Ne kete kapitull ne nuk do
perqendrohemi ne mesimin e SQL. Thjesht do te tregojme se si mund te
perdorim SQL per te patur kontroll ne tabelat e krijuara te bazes se te
dhenave.
Klikoni ne vetine RecordSource. Do te shfaqet dialog box_i Property
Pages. Ne kutine Command Text (SQL) shkruani kete rresht:
SELECT * FROM TableName
Kjo shprehje do te selektoje te gjitha fushat nga tabela me emrin
TableName ne bazen e te dhenave. Klikoni me tej OK.
Percaktimi i vetise RecordSource gjithashtu vendos vetine Recordset, te
cilen sic do ta shikojme me vone eshte nje veti shume e rendesishme.
Programim object-oriented Faqa 324
Ne menyre te permbledhur, lidha ndermjet data control dhe dy vetive te saj
kryesore (ConnectionString dhe RecordSource) eshte:
Programim object-oriented Faqa 325
Data Tools te lidhur (bound)
Pjesa me e madhe e veglave (tools) apo kontrolleve qe ne kemi studiuar ne
Visual Basic mund te perdoren si kontrolle te lidhur (bound) ose
informues te dhenash (data-aware). Kjo do te thote qe disa veti mund te
lidhen me nje fushe te vecante (posacem) te bazes se te dhenave. Per te
perdorur nje bound kontroll ne forme duhet te jene nje ose disa data control.
Disa bound data tools jane:
Label
Text Box
Check Box
Combo Box
List Box
Picture Box
Image Box
Gjithashtu jane edhe tre data ware tools:
1. DataCombo (me i mire se perdorimi bound combo box)
2. DataList (me I mire se bound list box),
3. Dhe DataGrid tools, te cilen do ta shikojme me vone.
Programim object-oriented Faqa 326
Vetite e Bound Tool
DataChanged Tregon nqs nje vlere e shfaqur ne nje bound
control ka ndryshuar.
DataField Specifikon emrin e fushes ne tabelen e treguar
nga data control_i respektiv.
DataSource Specifikon cili kontroll eshte i lidhur me data
control_in.
Nqs nje e dhene ne nje kontroll data-aware ndryshohet dhe me tej
perdoruesi fokusohet ne nje kontroll apo vegel tjeter, baza e te dhenave
do te perditesohet automatikisht me te dhenen e re (duke supozuar se
LockType eshte vendosur qe te lejoje ndonje modifikim)
Per te perdorur sa me thjeshte kontrollet bound, ndiqni keto hapa (sipas
radhes se listuar) per vendosjen e kontrolleve ne forme:
1. Vendosni kontrollin bound ne te njejten forme me data
control_in qe do te lidhet.
2. Vendosni vetine DataSource. Klikoni shigjeten per te listuar
data controls te formes tuaj. Zgjidhni nje prej tyre.
3. Vendosni vetine DataField. Klikoni shigjeten per te listuar
fushat qe lidhen me regjistrimin e data control_it te zgjedhur.
Beni nje zgjedhje.
4. Vendosni vetite e tjera, sipas kerkesave.
Duke ndjekur sipas radhes keto hapa, shmangni gabime qe mund te
ndodhin gjate aksesimit te te dhenave.
Programim object-oriented Faqa 327
Lidhjet ndermjet bound data control dhe data control jane:
Programim object-oriented Faqa 328
Example 7-1
Accessing the Books Database
1. Start a new application. We’ll develop a form where we can skim through
the books database, examining titles and ISBN values. Place an ADO data
control, two label boxes, and two text boxes on the form.
2. If you haven’t done so, create a data link for the BIBLIO.MDB database
following the steps given under Data Links in these notes.
3. Set the following properties for each control. For the data control and the
two text boxes, make sure you set the properties in the order given.
Form1:
BorderStyle 1-Fixed Single
Caption Books Database
Name frmBooks
Adodc1:
Caption Book Titles
ConnectionString BIBLIO.UDL (in whatever folder you saved it in -
select, don’t type)
RecordSource SELECT * FROM Titles
Name dtaTitles
Programim object-oriented Faqa 329
Label1:
Caption Title
Label2:
Caption ISBN
Text1:
DataSource dtaTitles (select, don’t type)
DataField Title (select, don’t type)
Locked True
MultiLine True
Name txtTitle
Text [Blank]
Text2:
DataSource dtaTitles (select, don’t type)
DataField ISBN (select, don’t type)
Locked True
Name txtISBN
Text [Blank]
When done, the form will look something like this (try to space your controls
as shown; we’ll use all the blank space as we continue with this example):
Programim object-oriented Faqa 330
4. Save the application. Run the application. Cycle through the various
book titles using the data control. Did you notice something? You didn’t
have to write one line of Visual Basic code! This indicates the power
behind the data tool and bound tools.
Programim object-oriented Faqa 331
Krijimi i nje tabele virtuale
Shpesh here, nje tabele ne bazen e te dhenave ka me shume informacione
se sa ne duam te shohim ose nje tabele nuk i ka te gjithe informacionet qe
ne duam te shohim. Psh, ne shembullin 8-1, shikimi i titullit dhe ISBN se nje
libri nuk eshte realisht informuese - ne mund te duam te shohim gjithashtu
Autorin, por ky informacion nuk sigurohet nga tabela Titles. Ne kete rast, ne
mund te ndertojme tabelen tone virtuale, duke shfaqur ne te vetem
informacionin qe perdoruesi deshiron te shikoje.
Per kete nevojitet krijimi i nje shprehje SQL ne vetine RecordSource.
Theksojme serisht qe nuk do te merremi me studimin e SQL, por do te japim
shprehje te gatshme.
Quick Example: Formimi i Tabeles Virtuale
1. We’ll use the results of Example 8-1 to add the Author name to the form.
Replace the RecordSource property of the dtaTitles control with the
following SQL statement:
SELECT Author,Titles.ISBN,Title FROM Authors,[Title Author],Titles
WHERE Authors.Au_ID=[Title Author].Au_ID AND
Titles.ISBN=[Title Author].ISBN ORDER BY Author
This must be typed as a single line in the Command Text (SQL) area that
appears when you click the ellipsis by the RecordSource property. Make sure
it is typed in exactly as shown. Make sure there are spaces after ‘SELECT’,
Programim object-oriented Faqa 332
after ‘Author,Titles.ISBN,Title’, after ‘FROM’, after ‘Authors,[Title
Author],Titles’, after ‘WHERE’, after ‘Authors.Au_ID=[Title Author].Au_ID’,
after ‘AND’, after ‘Titles.ISBN=[Title Author].ISBN’, and separating the final
three words ‘ORDER BY Author’. The program will tell you if you have a
syntax error in the SQL statement, but will give you little or no help in telling
you what’s wrong.
Here’s what this statement does: It selects the Author, Titles.ISBN, and Title
fields from the Authors, Title Author, and Titles tables, where the respective
Au_ID and ISBN fields match. It then orders the resulting virtual table, using
authors as an index.
2. Add a label box and text box to the form, for displaying the author name.
Set the control properties.
Label3:
Caption Author
Text1:
DataSource dtaTitles (select, don’t type)
DataField Author (select, don’t type)
Locked True
Name txtAuthor
Text [Blank]
Programim object-oriented Faqa 333
When done, the form should resemble this:
3. Ruani dhe ekzekutoni serisht aplikacionin. The author’s names will now
appear with the book titles and ISBN values. Did you notice you still
haven’t written any code? I know you had to type out that long SQL
statement, but that’s not code, technically speaking. Notice how the
books are now ordered based on an alphabetical listing of authors’ last
names.
Programim object-oriented Faqa 334
Gjetja e Regjistrimeve Specifike
Per perdorimin e data control per levizjen ndermjet regjistrimeve te bazes se
te dhenave, duhet te shkruajme rreshta kodi ne Visual Basic per te kryer
detyra te ndryshme. Per kete fakt i referohemi me emertimin
programmatic control. Shpesh here vetia Visible e data control eshte
False dhe gjithe perpunimet kryhen (ekzekutohen) ne kod. Gjithashtu ne
mund te perdorim programmatic control per gjetjen e rekordeve te caktuara.
Ka kater menyra per te levizur ne bazen e te dhenave. There are four
methods used for moving in a database. Keto metoda perserisin mundesite e
kater shigjetave te data control:
MoveFirst Leviz ne regjistrimin e pare te tabeles.
MoveLast Leviz ne regjistrimin e fundit te tabeles.
MoveNext Leviz ne regjistrimin e pasardhes (duke iu
referuar regjistrimit actual) te tabeles.
MovePrevious Leviz ne regjistrimin e parardhes (duke iu
referuar regjistrimit actual) te tabeles.
Kur levizim neper bazen e te dhenave me ane te programimit, duhet te
testojme vetite BOF (beginning of file) dhe EOF (end of file). Vetia BOF
eshte True kur regjistrimi aktual eshte i pozicionuar para ndonje te dhene.
Vetia EOF eshte True kur regjistrimi aktual ka qene perpara fundit te te
dhenave. Nqs secila nga vetite eshte True, regjistrimi actual eshte I
papranueshem. Nqs te dyja vetite jane True, ath nuk ka asnje te dhene ne
tabelen e bazes se te dhenave. then there is no data in the database table at
all.
Programim object-oriented Faqa 335
Keto veti, dhe metodat e programmatic control, ndikojne ne vetine
Recordset te data control. Prandaj, per te levizur ne regjistrimin e pare te
tabeles qe i eshte bashkangjitur nje data control me emrin dtaExample, do
te shkruajme kete sintakse:
dtaExample.Recordset.MoveFirst
Ekzistone nje metode qe perdoret per kerkimin ne nje baze te dhenash:
Find Gjen nje regjistrim qe ploteson nje kriter te
caktuar kerkimi.
Kjo metode gjithashtu ndikon ne vetine Recordset dhe ka tre argumenta qe
lidhen me te. Per perdorimin e Find me nje data control emertuar
dtaExample:
dtaExample.Recordset.Find Criteria,NumberSkipped,SearchDirection
Kontrolli Criteria eshte nje shprehje e ngjashme me fjalen WHERE ne nje
SQL. Ne kete leksion nuk do te japim shume detaje se criteria. Kriteri
cileson se cilet regjistrime te vecanta do te shfaqen. Psh, duke perdorur
bazen e te dhenave te librave, nqs ne duam te shikome librat te cilave u
fillon titulli (fusha Title) me S, do te perdorim:
Criteria = “Title >= ‘S’”
Theksojme perdorimin e thonjezave teke rreth germs se kerkimit. Thonjezat
teke perdoren per te futur (rrethuar) stringjet (vargjet) ne shprehjet e
Criteria. Tre operatore logjike mund te perdoren: barazimi (=), me e madhe
se (>), dhe me e vogel se (<).
Argumenti NumberSkipped tregon sa regjistrime te kalohen perpara se te
filloje Find. Mund te perdoret per te perjashtuar regjistrimin aktiv duke
caktuar NumberSkipped = 1.
Programim object-oriented Faqa 336
Argumenti SearchDirection ka dy mundesi: adSearchForward ose
adSearchBackward. Theksojme se ne nderthurje me 4 matodat e Move,
argumenti SearchDirection mund te perdoret per te siguruar nje mori tipesh
te ndryshme kerkimi (kerkim nga fillimi, kerkim nga fundi, etj.)
Nqs nje kerkim deshton ne gjetjen e regjistrimeve qe plotesojne kriterin,
vetia EOF ose BOF te Recordset _it vendoset True (ne varesi te drejtimit te
kerkimit).Nje veti tjeter e perdorur ne kerkime eshte Bookmark. Kjo veti ju
lejon te ruani treguesin e regjistrimit aktual ne ato raste kur doni te ktheheni
ne ate pozicion me vone.
Programim object-oriented Faqa 337
Example 7-2
‘Rolodex’ Searching of the Books Database
1. We expand the book database application to allow searching for certain
author names. We’ll use a ‘rolodex’ approach where, by pressing a
particular letter button, books with author last names corresponding to
that button appear on the form.
2. We want a row of buttons starting at ‘A’ and ending at ‘Z’ to appear on
the lower part of our form. Drawing each one individually would be a big
pain, so we’ll let Visual Basic do all the work in the Form_Load
procedure. What we’ll do is create one command button (the ‘A’), make it
a control array, and then dynamically create 25 new control array
elements at run-time, filling each with a different letter. We’ll even let the
code decide on proper spacing.
So, add one command button to the previous form. Name it cmdLetter
and give it a Caption of A. Set its Index property to 0 to make it a
control array element. On my form, things at this point look like this:
Programim object-oriented Faqa 338
3. Attach this code to the Form_Load procedure. This code sets up the
rolodex control array and draws the additional 25 letter buttons on the
form. (Sorry, you have to type some code now!)
Private Sub Form_Load()
Dim I As Integer
‘Size buttons
cmdLetter(0).Width = (frmBooks.ScaleWidth - 2* cmdLetter(0).Left) / 26
For I = 1 To 25
Load cmdLetter(I) ' Create new control array element
'Position new letter next to previous one
cmdLetter(I).Left = cmdLetter(I - 1).Left + cmdLetter(0).Width
'Set caption and make visible
cmdLetter(I).Caption = Chr(vbKeyA + I)
cmdLetter(I).Visible = True
Next I
End Sub
At this point, even though all the code is not in place, you could run your
application to check how the letter buttons look. My finished form (at run-
time) looks like this:
Programim object-oriented Faqa 339
Notice how Visual Basic adjusted the button widths to fit nicely on the form.
Programim object-oriented Faqa 340
4. Attach this code to the cmdLetter_Click procedure. In this procedure,
we use a search criteria that finds the first occurrence of an author name
that begins with the selected letter command button. If the search fails,
the record displayed prior to the search is retained (using the Bookmark
property).
Private Sub cmdLetter_Click(Index As Integer)
Dim BookMark1 As Variant
'Mark your place in case no match is found
BookMark1 = dtaTitles.Recordset.Bookmark
'Move to top of table to start search
dtaTitles.Recordset.MoveFirst
dtaTitles.Recordset.Find "Author >= '" + cmdLetter(Index).Caption + "'", 0, adSearchForward
If dtaTitles.Recordset.EOF = True Then
dtaTitles.Recordset.Bookmark = BookMark1
End If
txtAuthor.SetFocus
End Sub
Let’s look at the search a little closer. We move to the top of the
database using MoveFirst. Then, the Find is executed (notice the
selected letter is surrounded by single quotes). If EOF is True after the
Find, it means we didn’t find a match to the Criteria and Bookmark is
returned to its saved value.
Programim object-oriented Faqa 341
5. Save your application. Test its operation. Note once the program finds
the first occurrence of an author name beginning with the selected letter
(or next highest letter if there is no author with the pressed letter), you
can use the data control navigation buttons (namely the right arrow
button) to find other author names beginning with that letter.
Programim object-oriented Faqa 342
Data Manager
Deri tani ne kemi pare se si mund te perdorim data control per aksesimin e
nje baze te dhenash. Fuqia e Visual Basic gjendet ne aftesite e tij per te
manipuluar regjistrimet me ane te kodit. lies in its ability to manipulate
records in code. Disa detyra si percaktimi I vlerave ne fusha te vecanta,
shtimi i regjistrimeve, fshirja e regjistrimeve dhe levizja neper regjistrime
mund te behen lehtesisht. Kjo ju lejon te ndertoni nje system te plote
menaxhimi te bazes se te dhenave (database management system DBMS).
Per te mos ndryshuar shembullin e bazes se te dhenave, BIBLIO.MDB, le te
krijojme nje baze te dhenash tonen, te cilen do ta ndryshojme. Per kete na
vjen ne ndihme Visual Basic. Visual Data Manager eshte nje Visual Basic
Add-In qe lejon krijimin dhe menaxhimin e bazave te te dhenave. Eshte
shume I thjeshte ne perdorim dhe mund te ndertoje nje baze te dhenash
kompatibel (te pajtueshme) me Microsoft Jet (ose Access) database engine.
Per te ekzaminuar nje baze te dhenash ekzistuese duke perdorur Data
Manager, ndiqni hapat me poshte:
1. Zgjidhni Visual Data Manager nga menuja Add-In e Visual
Basic (mund te pyeteni nese doni te shtoni SYSTEM.MDA ne
skedarin.INI – pergjigjuni me No.)
2. Zgjidhni Open Database nga menuja Data Manager File.
3. Zgjidhni tipin dhe emrin e bazes se te dhenave qe doni te
kontrolloni.
Ne kohen kur baza e te dhenave eshte hapur, mund te beni shume
veprime. Thjesht mund te shikoni ndermjet tabelave te ndryshme, mund
te kerkoni per regjistrime te vecanta, mund te zbatoni SQL queries, mund
te shtoni /fshini regjsitrime. Data Manager ne vetevete eshte DBMS.
Programim object-oriented Faqa 343
Perdorni Data Manager per tu njohur me shembullin e bazes se te
dhenave BIBLIO.MDB.
Per te krijuar nje baze te re, ndiqni hapat me poshte:
1. Zgjidhni Visual Data Manager nga menuja Add-In e Visual
Basic (mund te pyeteni nese doni te shtoni SYSTEM.MDA ne
skedarin.INI – pergjigjuni me No.)
2. Zgjini New nga menuja Data Manager File. Zgjidhni tipin e
bazes se te dhenave, zgjidhni dosjen dhe shkruani emrin per
bazes e te dhenave. Klikoni OK.
3. Do te hapet dritarja e bazes se te dhenave. Klikoni me butonin e
djathte te mous_it ne dritare dhe zgjidhni komanden New
Table. Ne kutine Name, shkruani emrin e tabeles. Me pas
percaktoni fushat e tabeles, nje e nga nje duke klikuar Add
Field, shkruani emrin e fushes, percaktoni tipin e te dhenes, dhe
nqs kerkohet specifikoni madhesine e fushe. Sapo fusha te jete
percaktuar, klikoni butonin OK per ta shtuar ate ne kutine e
fushave. Pasi keni percaktuar gjithe fushat, per te ruajtur tabelen
tuaj klikoni butonin Build the Table.
Programim object-oriented Faqa 344
Example 7-3
Udhezuesi i Numrave te Telefonit – Krijimi i bazes se te
dhenave
Me kete shembull, do te fillojme zhvillimin e nje aplikacioni per nje
udhezues (liste e renditur) te thjeshte telefonik. Ne udhezues, do te
mbajme informacion per emrat dhe numrat e telefonit. Do tem und te
modifikojme, shtojme dhe fshijme emra dhe numra telefoni nga ky
udhezues. Gjithashtu do te bejme kerkime per emra te ndryshem. Ne
kete hap te pare, do te percaktojme strukturen e bazes se te dhenave
qe do te perdorim. Udhezuesi telefonik do te kete nje tabele te vetme
me tre fusha: Name, Description, dhe Phone. Name do te
permbaje emrin e nje njeriu apo kompanie, Description do te
permbaje nje shprehje pershkruese (nqs deshironi) se kush eshte
njeriu apo kompania, dhe Phone do te mbaje numrin e telefonit.
Hapni Data Manager. Ndiqni hapat e percaktuara me siper per krijimin
e nje baze te re te (Microsoft Access). Perodrini PhoneList si emer per
tabelen e bazes se te dhenave. Percaktoni tre fusha, secila prej tyre
duhet te kete e tipit Text, caktojini fushave Name dhe Description
madhesine (size) 40, fushes Phone madhesine 15. Pasi te jene
percaktuar gjithe fushat, ekrani do te duket si me poshte:
Programim object-oriented Faqa 345
Pasi keni mbaruar me percaktimin e fushave, klikoni Build the Table
per te ruajtur tabelen e re. Pas ketij hapi do te ktheheni ne dritaren
Database Tables.
Tani ju jeni gati te hidhni disa te dhena ne bazen tuaj te te dhenave, Ne
dritaren Database, klikoni me butonin e djathte te mous_it mbi tabelen
PhoneList dhe zgjidhni Open. Do ju shfaqet dritarja me poshte:
Programim object-oriented Faqa 346
Ne kete moment, hidhni disa regjistrime (te pakten 5). Hapat per cdo
regjistrim jane: klikoni Add per shtimin e regjistrimi, (2) mbushni tre fushat
(apo te pakten fushat Name dhe Phon), dhe (3) klikoni Update per te
ruajtur permbajtjen.
Gjithashtu nese deshironi mund te fshini dhe te kerkoni (Delete dhe Fin.
Mund te levizni neper regjistrime duke perdorur ashensorin (scroll bar) ne
fund te dritares. Pasi keni mbaruar me hedhjen e te dhenave, Close per te
ruajtut punen tuaj. Zgjidhni Exit nga menuja Data Manager File. Tashme
baza juaj e te dhenave eshte krijuar.
Programim object-oriented Faqa 347
Menaxhimi i Bazes se te Dhenave (Database Management)
Data Manager eshte nje vegel e shumeanshme per te krijuar dhe pare baza
te dhenash. Megjithate, nderfaqa e saj nuk eshte shume e kendshme dhe
perdorimi i saj shpesh here eshte i veshtire. Ne nuk kemi qellim ta perdorim
ate si nje database management system (DBMS). Gjithashtu nuk presim
qe perdoruesi te kete te disponueshem per perdorimin e tij Data Manager_in.
Hapi tjeter ne zhvillimin e njohurive te bazave te te dhenave eshte perodrimi
i Visual Basic per menaxhimin e bazave te te dhenave, to manage our
databases, qe eshte zhvillimi i nje DBMS.
Do te zhvillojme nje DBMS te thjeshte. Kjo do te na lejoje te shohim
regjistrimet ne nje baze ekzistuese te dhenash. Do te jemi ne gjendje te
modifikojme, shtojme dhe fshijme regjistrime. Detyra te avancuara si shtimi
i tabelave dhe fushave ne nje baze te dhenash mund te behen me Visual
Basic, por nuk eshte ky qellimi i diskutimit ne kete leksion.
Per te krijuar DBMS tone, duhet te percaktojme disa metoda te tjera
kontrollesh te programueshme te bashkuara me vetine Recordset te data
control. These methods are:
AddNew Shton nje regjistrim te ri ne tabele. Gjithe
fushat behen Null dhe ky regjistrim eshte
regjistrimi actual
Delete Fshin regjistrimin actual nga tabela. Kjo
metode duhet te pasohet menjehere me nje
Programim object-oriented Faqa 348
nga metodat e Move sepse regjistrimi actual
eshte i pavlefshem pas fshirjes.
Update Ruan permbajtjet aktuale per gjithe bound
tools.
Per te perditesuar nje regjistrim actual (edit), thjesht duhet te shfaqni
regjistrimin dhe te beni ndryshimet e kerkuara. Vetia LockType duhet te
jete vendosur adLockPessimistic. Kur zhvendoseni nga ky regjistrim, me
cdonjerin nga butonat e navigimit apo nepermjet ndonje veprimi tjeter,
Visual Basic do te perditesoje automatikisht regjistrimin. Sipas deshires apo
nevojes, ju mund te therrisni metoden Update per te detyruar nje
perditesim (perdorni LockType = asLockOptimistic). Per nje data control
me emrin dtaExample, sintaksa per kete shprehje eshte:
dtaExample.Recordset.Update
Per te shtuar nje regjistrim ne bazen e te dhenave (add), therrasim
metoden AddNew. Sintaksa per shembullin tone te data control_it eshte:
dtaExample.Recordset.AddNew
Kjo shprehje do te boshatisi ‘bound data tools’ dhe do te zhvendose
regjistrimin actual ne fund te tabeles. Ne kete moment, ju hidhni vlerat e
reja. Kur zhvendoseni nga ky regjistrim, ndryshimet behen automatikisht
nga baza e te dhenave. Njo menyre tjeter per perditesimin e bazes se te
dhenave eshte me ane te metodes Update.
Pas shtimit te regjistrimit ne bazen e te dhenave, per te siguruar renditjen e
duhur (e vendosur nga shprehja RecordSource SQL) te regjistrimit te ri
duhet te therrisni vetine Refresh . Formati eshte:
dtaExample.Refresh
Programim object-oriented Faqa 349
Per te fshire nje regjistrim nga baza e te dhenave (delete),
sigurohuni qe regjistrimi qe do te fshini eshte regjistrimi actual. Me
pas perdorim metoden Delete. Sintaksa per data control me emrin
dtaExample eshte: dtaExample.Recordset.Delete
Sapo ekzekutoni nje Delete, duhet te zhvendoseni (duke perdorur nje nga
metodat e ‘Move’) nga regjistrimi actual sepse nuk ekziston me, nese nuk
zhvendoseni do te gjenerohet nje gabim. Kur fshini regjistrimin e fundit
kontrolloni vetine EOF. Nqs EOF eshte true, duhet te zhvendoseni ne
fillim te bazes se te dhenave (MoveFirst). Me pas duhet te siguroheni qe
aty eshte nje regjistrim i vlefshem (kontrolloni BOF).
Programim object-oriented Faqa 350
Example 7-4
Udhezuesi i Numrave te Telefonit – Menaxhimi i Bazes se
te Dhenave
1. Before starting, make a copy of your phone database file using the
Windows Explorer. That way, in case we mess up, you still have a
good copy. And, create a data link to the database. Here, we develop
a simple DBMS for our phone number database. We will be able to
display individual records and edit them. And, we will be able to add
or delete records. Note this is a simple system and many of the fancy
‘bells and whistles’ (for example, asking if you really want to delete a
record) that should really be here are not. Adding such amenities is
left as an exercise to the student.
2. Load your last Books Database application (Example 8-2 - the one with
the ‘Rolodex’ search). We will modify this application to fit the phone
number DBMS. Resave your form and project with different names.
Add three command buttons to the upper right corner of the form.
Modify/set the following properties for each tool. For the data control
and text boxes, make sure you follow the order shown.
frmBooks (this is the old name):
Caption Phone List
Name frmPhone
dtaTitles (this is the old name):
Caption Phone Numbers
Programim object-oriented Faqa 351
ConnectionString [your phone database data link] (select, don’t
type)
RecordSource SELECT * FROM PhoneList ORDER BY Name (the
ORDER keyword sorts the database by the given
field)
Name dtaPhone
LockType adLockOptimistic
Label1:
Caption Description
Label2:
Caption Phone
Label3:
Caption Name
txtAuthor (this is the old name):
DataSource dtaPhone (select, don’t type)
DataField Name (select, don’t type)
Locked False
Name txtName
MaxLength 40
TabIndex 1
txtISBN (this is the old name):
Programim object-oriented Faqa 352
DataSource dtaPhone (select, don’t type)
DataField Phone (select, don’t type)
Locked False
Name txtPhone
MaxLength 15
TabIndex 3
txtTitle (this is the old name):
DataSource dtaPhone (select, don’t type)
DataField Description (select, don’t type)
Locked False
Name txtDesc
MaxLength 40
TabIndex 2
Command1:
Caption &Add
Name cmdAdd
Command2:
Caption &Save
Enabled False
Name cmdSave
Command3:
Programim object-oriented Faqa 353
Caption &Delete
Name cmdDelete
When done, my form looked like this:
At this point, you can run your application and you should be able to
navigate through your phone database using the data control. Don’t try any
other options, though. We need to do some coding.
3. In Form_Load, replace the word frmBooks with frmPhone. This will
allow the letter keys to be displayed properly.
4. In the cmdLetter_Click procedure, replace all occurrences of the word
dtaTitles with dtaPhone. Replace all occurrences of Author with
Name. The modified code will be:
Private Sub cmdLetter_Click(Index As Integer)
Dim BookMark1 As Variant
Programim object-oriented Faqa 354
'Mark your place in case no match is found
BookMark1 = dtaPhone.Recordset.Bookmark
dtaPhone.Recordset.MoveFirst
dtaPhone.Recordset.Find "Name >= '" + cmdLetter(Index).Caption + "'"
If dtaPhone.Recordset.EOF = True Then
dtaPhone.Recordset.Bookmark = BookMark1
End If
txtName.SetFocus
End Sub
5. Attach this code to the cmdAdd_Click procedure. This code invokes
the code needed to add a record to the database. The Add and
Delete buttons are disabled. Click the Save button when done adding
a new record.
Private Sub cmdAdd_Click()
cmdAdd.Enabled = False
cmdSave.Enabled = True
cmdDelete.Enabled = False
dtaPhone.Recordset.AddNew
txtName.SetFocus
End Sub
6. Add this code to the cmdSave_Click procedure. When done entering
a new record, the command button status’s are toggled, the Recordset
Programim object-oriented Faqa 355
updated, and the data control Refresh method invoked to insure proper
record sorting.
Private Sub cmdSave_Click()
dtaPhone.Recordset.Update
dtaPhone.Refresh
cmdAdd.Enabled = True
cmdSave.Enabled = False
cmdDelete.Enabled = True
txtName.SetFocus
End Sub
7. Attach this code to the cmdDelete_Click procedure. This deletes the
current record and moves to the next record. If we bump into the end
of file, we need to check if there are no records remaining. If no
records remain in the table, we display a message box. If records
remain, we move around to the first record.
Private Sub cmdDelete_Click()
dtaPhone.Recordset.Delete
dtaPhone.Recordset.MoveNext
If dtaPhone.Recordset.EOF = True Then
dtaPhone.Refresh
If dtaPhone.Recordset.BOF = True Then
MsgBox "You must add a record.", vbOKOnly + vbInformation, "Empty file"
Call cmdAdd_Click
Programim object-oriented Faqa 356
Else
dtaPhone.Recordset.MoveFirst
End If
End If
txtName.SetFocus
End Sub
8. Save the application. Try running it. Add records, delete records, edit
records. If you’re really adventurous, you could add a button that dials
your phone (via modem) for you! Look at the custom communications
control.
Programim object-oriented Faqa 357
Kontrollet per Informimin e te Dhenave (Custom Data Aware Controls)
Sic e kemi permendur me pare, pervec veglave standarte te Visual Basic , ka
tre vegla per informimin dhenash (custom data aware tools):
1. DataList,
2. DataCombo,
3. dhe DataGrid ADO
Do te paraqesim secilen prej tyre, duke dhene sygjerime per perdorimin e
secilit prej tyre, disa veti dhe disa ngjarje. Nqs ikonat e ketyre veglave nuk
jane ne toolbox, zgjidhni menune Project, me pas klikoni Components. Ne
dritaren Components zgjidhni Microsoft DataList Controls 6.0 (OLEDB)
dhe Microsoft DataGrid 6.0 (OLEDB). Klikoni OK – kontrollet do te
shfaqen ne toolbox.
Ashtu si data control, Versionet e meparshme te Visual Basic kane perdorur
versionin DAO te kontrolleve list, combo, dhe grid, emertuar DBList,
DBCombo, dhe DBGrid. Sigurohuni qe nuk jeni duke perdorur keto vegla
pune.
Programim object-oriented Faqa 358
DataList Box
Vegla e pare e punes ‘bound data’ eshte DataList Box. List box mbushet
automatikisht me fushen e data control_it te specifikuar. Selektimet nga
list box mund te perdoren per perditesimin e nje fushe tjeter nga e njejta
data control ose sipas deshires per perditesimin e nje fushe nga nje data
control tjeter.
Disa veti te DataList box jane:
DataSource Emri i data control qe u ndryshua me ane te
selektimit.
DataField Emri i fushes se ndryshuar ne Recordset
caktuar nga DataSource.
RowSource Emri i data control_it qe perdoret si burim per
elementet ne list box.
ListField Emri i fushes caktuar nga RowSource ne
Recordset qe perdoret per te list box.
BoundColumn Emri i fushes caktuar nga RowSource ne
Recordset qe do ti kalohet DataField, ne kohen
kur selektimi eshte bere. Ne pergjithesi eshte e
njejte si ListField.
Programim object-oriented Faqa 359
BoundText Vlera Text e fushes BoundColumn. Kjo eshte
vlera qe i kalohet vetise DataField.
Text Vlera Text e elementit te zgjedhur ne liste. Ne
pergjithesi e njejte si BoundText.
Perdorimi me i perhapur i DataList box eshte per te mbushur listen nga
baza e te dhenave, me pas lejon selektime. Selektimi mund te perdoret
me pas per te mbushur ndonje vegel ne forme, qofte ajo informuese te
dhenash (data aware) ose jo
Si shembull, me poshte jepet nje DataList box e mbushur me fushen
Title (ListField) te data control_it dtaExample (RowSource). Data
control_i eshte i lidhur me tabelen Titles ne bazen e te dhenave
BIBLIO.MDB.
Programim object-oriented Faqa 360
DataCombo Box
DataCombo Box eshte afersisht identik me DataList box. Ndryshimi I
vetem ndermjet tyre eshte qe me DataCombo box, lista shfaqet si nje
drop-down box dhe perdoruesit i jepet mundesia te ndryshoje permbajtjen
qe kthehet per vetine Text.
Programim object-oriented Faqa 361
DataGrid Tool
Vegla DataGrid eshte vegla me e perdorshme per informim te dhenash.
Me ane te saj mund te shfaqet permbajtja e plote e tabeles se nje baze te
dhenash, tabele e adresuar nga nje data control. Me tej tabela mund te
editohet sipas deshires.
E vetmja veti ku ne do perqendrohemi eshte DataSource, e cila si
githmone, identifikon tabelen qe lidhet data control_i perkates.
Si shembull per fuqine e kontrollit DataGrid, me poshte tregohet se cfare
arrihet thjesht duke vendosur vetine DataSource te data control_it
dtaExample, i cili eshte i lidhur me tabelen Titles ne bazen e te dhenave
BIBLIO.MDB:
Programim object-oriented Faqa 362
Ne kete pike, mund te levizim permes tabeles dhe te modifikojme ndonje
vlere qe zgjedhim. Ndryshimet reflektohet automatikisht ne bazen
qendrore. Gjeresia e kollonave mund te ndryshohet gjate kohes se
ekzekutimit (run-time)! Eshte I mundur selektimi disa rreshtave dhe
kollonave. Ashtu si thame dhe me siper eshte nje vegel shume e
fuqishme.
Programim object-oriented Faqa 363
Krijimi i Data Report
Pasi keni zhvilluar dhe menaxhuar nje baze te dhenash, eshte shume mire te
keni mundesi per te siguruar informacione te printuara apo te shfaqura ne
ekran nga te dhenat tuaja. Procesi i sigurimit te ketyre informacioneve njihet
si krijimi i nje raporti te dhenash (data report).
Ka dy hapa qe duhet te ndiqen per krijimin e nje raporti te dhenash.
Fillimisht duhet te krijohet ambient i te dhenave (Data Environment). Kjo
eshte e dizenjuar brenda Visual Basic dhe perdoret per ti treguar raportit te
te dhenave se cfare kemi ne bazen e te dhenave.
Se dyti, krijohet vete Data Report. Gjithashtu dhe kjo behet brenda Visual
Basic. Skedaret Data Environment dhe Data Report behen pjese e projektit
te zhvilluar ne Visual Basic.
Aftesite e data report te Visual Basic 6.0 jane te pafundme dhe perdorimi i
tyre eshte nje process i hollesishem. Perdorimi i ketyre aftesive eshte me
mire te tregohet me shembuj. Do te shohim bazat e krijimit te raporteve
duke krijuar nje raport per bazen e te dhenave te telefonave.
Programim object-oriented Faqa 364
Example 8-5
Phone Directory - Building a Data Report
We will build a data report that lists all the names and phone numbers in our
phone database. We will do this by first creating a Data Environment, then a
Data Report. We will then reopen the phone database management project
and add data reporting capabilities.
Creating a Data Environment
1. Start a new Standard EXE project.
2. On the Project menu, click Add Data Environment. If this item is not
on the menu, click Components. Click the Designers tab, and choose
Data Environment and click OK to add the designer to your menu.
3. We need to point to our database. In the Data Environment window,
right-click the Connection1 tab and select Properties. In the Data Link
Properties dialog box, choose Microsoft Jet 3.51 OLE DB Provider.
Click Next to get to the Connection tab. Click the ellipsis button. Find
your phone database (mdb) file. Click OK to close the dialog box.
4. We now tell the Data Environment what is in our database. Right-click the
Connection1 tab and click Rename. Change the name of the tab to
Phone. Right-click this newly named tab and click Add Command to
create a Command1 tab. Right-click this tab and choose Properties.
Assign the following properties:
Programim object-oriented Faqa 365
Command Name PhoneList
Connection Phone
DataBase Object Table
ObjectName PhoneList
5. Click OK. All this was needed just to connect the environment to our
database.
6. Display the properties window and give the data environment a name
property of denPhone. Click File and Save denPhone As. Save the
environment in an appropriate folder. We will eventually add this file to
our phone database management system. At this point, my data
environment window looks like this (I expanded the PhoneList tab by
clicking the + sign):
Programim object-oriented Faqa 366
Creating a Data Report
Once the Data Environment has been created, we can create a Data Report.
We will drag things out of the Data Environment onto a form created for the
Data Report, so make sure your Data Environment window is still available.
1. On the Project menu, click Add Data Report and one will be added to
your project. If this item is not on the menu, click Components. Click
the Designers tab, and choose Data Report and click OK to add the
designer to your menu.
2. Set the following properties for the report:
Name rptPhone
Caption Phone Directory
DataSource denPhone (your phone data environment - choose,
don’t type)
DataMember PhoneList (the table name - choose don’t type)
3. Right-click the Data Report and click Retrieve Structure. This
establishes a report format based on the Data Environment.
4. Note there are five sections to the data report: a Report Header, a
Page Header, a Detail section, a Page Footer, and a Report Footer.
The headers and footers contain information you want printed in the
report and on each page. To place information in one of these regions,
right-click the selected region, click Add Control, then choose the control
you wish to place. These controls are called data report controls and
properties are established just like you do for usual controls. Try adding
some headers.
Programim object-oriented Faqa 367
5. The Detail section is used to layout the information you want printed for
each record in your database. We will place two field listings (Name,
Phone) there. Click on the Name tab in the Data Environment window
and drag it to the Detail section of the Data Report. Two items should
appear: a text box Name and a text box Name (PhoneList). The first
text box is heading information. Move this text box into the Page Header
section. The second text box is the actual value for Name from the
PhoneList table. Line this text box up under the Name header. Now, drag
the Phone tab from the Data Environment to the Data Report. Adjust the
text boxes in the same manner. Our data report will have page headers
Name and Phone. Under these headers, these fields for each record in
our database will be displayed. When done, the form should look
something like this:
Programim object-oriented Faqa 368
In this form, I’ve resized the labels a bit and added a Report Header. Also, make
sure you close up the Detail section to a single line. Any space left in this section
will be inserted after each entry.
6. Click File and Save rptPhone As. Save the environment in an appropriate
folder. We will now reopen our phone database manager and attach this and the
data environment to that project and add capabilities to display the report.
Accessing the Data Report
1. Reopen the phone directory project. Add a command button named cmdReport
and give it a Caption of Show Report. (There may be two tabs in your toolbox,
one named General and one named DataReport. Make sure you select from
the General tools.)
2. We will now add the data environment and data report files to the project. Click
the Project menu item, then click Add File. Choose denPhone and click OK.
Also add rptPhone. Look at your Project Window. Those files should be listed
under Designers.
3. Use this code in cmdReport_Click:
Private Sub cmdReport_Click()
rptPhone.Show
End Sub
4. This uses the Show method to display the data report.
5. Save the application and run it. Click the Show Report button and this should
appear:
Programim object-oriented Faqa 369
You now have a printable copy of the phone directory. Just click the Printer icon.
Notice the relationship with this displayed report and the sections available in
the Data Report designer.
Programim object-oriented Faqa 370
Exercise 7
Home Inventory Database
Design and develop an application that manages a home inventory database. Add
the option of obtaining a printed list of your inventoried property.
My Solution:
Database Design:
The first step is to design a database using Data Manager (or Access). My
database is a single table (named MYSTUFF). Its specifications are:
Field Name Field Type Field Length
Item Text 40
Serial Number Text 20
Date Purchased Text 20
New Value Currency <N/A>
Location Text 40
This database is saved as file HomeInv.mdb. Create a data link to your database.
The link is saved as HomeInv.udl.
Programim object-oriented Faqa 371
Report Design:
The second step is to use the Data Environment and Data Report designers to setup
how you want the printed home inventory to appear. Use your discretion here. My
final report design is saved in denHomeInv and rptHomeInv. We will access this
report from our Visual Basic application. My Data Report design looks like this:
Programim object-oriented Faqa 372
Project Design:
Form:
Properties:
Form frmHome:
BorderStyle = 1 - Fixed Single
Caption = Home Inventory
CommandButton cmdExit:
Caption = E&xit
ADO Data Control dtaHome:
Caption = Book Titles
ConnectionString = HomeInv.udl (in whatever folder you saved it in -
Programim object-oriented Faqa 373
select, don’t type)
RecordSource = SELECT * FROM MyStuff
Visible = False
CommandButton cmdShow:
Caption = Show &Report
CommandButton cmdPrevious:
Caption = &Previous Item
CommandButton cmdNext:
Caption = &Next Item
CommandButton cmdDelete:
Caption = &Delete Item
CommandButton cmdAdd:
Caption = &Add Item
TextBox txtLocation:
DataField = Location
DataSource = dtaHome
FontName = MS Sans Serif
FontSize = 9.75
MaxLength = 40
TextBox txtValue:
DataField = New Value
Programim object-oriented Faqa 374
DataSource = dtaHome
FontName = MS Sans Serif
FontSize = 9.75
TextBox txtDate:
DataField = Date Purchased
DataSource = dtaHome
FontName = MS Sans Serif
FontSize = 9.75
MaxLength = 20
TextBox txtSerial:
DataField = Serial Number
DataSource = dtaHome
FontName = MS Sans Serif
FontSize = 9.75
MaxLength = 20
TextBox txtItem:
DataField = Item
DataSource = dtaHome
FontName = MS Sans Serif
FontSize = 9.75
MaxLength = 40
Label Label5:
Programim object-oriented Faqa 375
Caption = Location
FontName = Times New Roman
FontSize = 12
Label Label4:
Caption = New Value
FontName = Times New Roman
FontSize = 12
Label Label3:
Caption = Purchase Date
FontName = Times New Roman
FontSize = 12
Label Label2:
Caption = Serial Number
FontName = Times New Roman
FontSize = 12
Label Label1:
Caption = Item
FontName = Times New Roman
FontSize = 12
Code:
General Declarations:
Programim object-oriented Faqa 376
Option Explicit
cmdAdd Click Event:
Private Sub cmdAdd_Click()
'Add new item to database
dtaHome.Recordset.AddNew
txtItem.SetFocus
End Sub
cmdDelete Click Event:
Private Sub cmdDelete_Click()
'Delete item from database
Dim Rvalue As Integer
Rvalue = MsgBox("Are you sure you want to delete this item?", vbQuestion + vbYesNo, "Delete Item")
If Rvalue = vbNo Then Exit Sub
dtaHome.Recordset.Delete
dtaHome.Recordset.MoveNext
If dtaHome.Recordset.EOF Then
If dtaHome.Recordset.BOF Then
MsgBox "You must add an item.", vbOKOnly + vbInformation, "Empty Database"
Call cmdAdd_Click
Else
dtaHome.Recordset.MoveFirst
End If
Programim object-oriented Faqa 377
End If
txtItem.SetFocus
End Sub
cmdExit Click Event:
Private Sub cmdExit_Click()
End
End Sub
cmdNext Click Event:
Private Sub cmdNext_Click()
'Move to next item - if at end-of-file, backup one item
dtaHome.Recordset.MoveNext
If dtaHome.Recordset.EOF Then dtaHome.Recordset.MovePrevious
txtItem.SetFocus
End Sub
Programim object-oriented Faqa 378
cmdPrevious Click Event:
Private Sub cmdPrevious_Click()
'Move to previous item - if at beginning-of-file, go down one item
dtaHome.Recordset.MovePrevious
If dtaHome.Recordset.BOF Then dtaHome.Recordset.MoveNext
txtItem.SetFocus
End Sub
cmdShow Click Event:
Private Sub cmdShow_Click()
rptHomeInv.Show
End Sub
Programim object-oriented Faqa 379
9. Gjuha Visual Basic. Disa
kontrolle te vecuara
Ne kete kapitull do te trajtojme disa kontrolle te vecuara dhe shembuj te
shkurter te perdorimit te tyre. Per secilin nga keto kontrolle do te shohim
disa nga vetite me te rendesishme, ngjarjet dhe metodat . Qellimi kryesor
eshte t’ju tregohet disa nga keto kontrolle. Ju mund te ‘germoni’ ne toolbox
dhe te shikoni te gjithe veglat qe ndodhen aty.
Programim object-oriented Faqa 380
Kontrolli Masked Edit
Kontrolli masked edit perdoret per te nxitur perdoruesit te hedhin te
dhenat duke perdorur nje dizenjo te maskuar. ‘Maska’ ju lejon te specifikoni
ekzaktesisht formatin e deshiruar te te dhenes. Ky kontroll duket si nje text
box standart dhe ngarkohet duke zgjedhur Microsoft Masked Edit
Control te dritaren Components.
Ky kontroll mund te perdoret:
Per shkrimin e nje date, ore, numri apo vlere monetare.
Per shkrimin e nje informacioni qe i bindet nje dizenjoje, si
psh nje numer telefoni apo numri i sigurimeve shoqerore.
Per te formuar paraqitjen dhe printimin e maskes se te
dhenave dalese.
Vetite e Masked Edit
Mask Percakton tipin e informacionit qe futet ne
kontroll. Perdoren karakteret per percaktimin e
tipin e te dhenes.
Text Permban te dhenen e hedhur ne kontroll.
Programim object-oriented Faqa 381
Ngjarjet e Masked Edit
Change Ngjarje qe thirret kur e dhena ne kontroll
ndryshon.
Validation ErrorNgjarje qe thirret kur e dhena e hedhur nga
perdoruesi nuk perputhet me input mask.
Shembull i Masked Edit:
Do te perdorim kontrollin masked edit per te siguruar nje numer telefoni.
Vendosni nje kontroll masked edit ne forme. Vendosni vetine Mask te
ketij kontrolli te barabarte:
(###)-###-####
Vendosni vetine Font Size = 12. Forma do te duket si me poshte:
Ekzekutoni shembullin dhe vereni se sa e thjeshte eshte te shkruash nje
numer telefoni.
Programim object-oriented Faqa 382
Kontrolli Chart
Kontrolli chart eshte nje vegel mahnitese. Ne fakt, ne vetvete ai duket si
nje program i plote. Ai ju lejon te dizenjoni te gjithe tipet e grafikeve ne
formen tuaj. Me pas, ne kohen e ekzekutimit (run-time), vizatoni grafiket,
printojini ata, bejini kopje dhe ndryshoni stilin e tyre. Kontrolli ngarkohet
duke zgjedhur nga dritarja Components , Microsoft Chart Control.
Perdorime te mundshme te kontrollit perfshijne:
Shfaqjen e te dhenave ne nje nga grafiket e shumte 2D ose
3D.
Ngarkimin e te dhenave ne nje rrjet koordinatash (grid) nga
nje tabele(matrice).
Veti te kontrollit Chart Control
ChartType Krijon tipin e grafikut.
RandomFill Perdoret per te mbushur grafikun me vlera te
rastesishme (random). Normalisht te dhenat
ngarkohen nga nje object data grid object te
lidhur me kontrollin chart .
Programim object-oriented Faqa 383
Sic duket nga dritarja e vetive, ka shume veti te tjera qe perdoren
me kontrollin chart. Ne do te ndalemi vetem te keto te dyja per te
ilustruar se cfare mund te behet me kete kontroll te fuqishem.
Shembuj per kontrollin Chart:
Hapni nje aplikacion te ri. Shtoni ne forme nje kontroll chart. Do te
shfaqet nje grafik standart i tipit ‘bar’:
Ndryshoni vetine ChartType ne 3 dhe fitoni keshtu nje grafik te tipit
‘line’:
Programim object-oriented Faqa 384
Programim object-oriented Faqa 385
Ose fitoni nje grafik 3D duke perdorur ChartType = 8:
Keta shembuj te shpejte ju japin nje vleresim per fuqine dhe lehtesise e
perdorimit te ketij kontrolli.
Programim object-oriented Faqa 386
Kontrolli Multimedia
Kontrolli multimedia ju lejon te administroni paisjet Media Control
Interface (MCI). Keto pasije perfshijne: karten e zerit, renditesit MIDI, CD-
ROM drives, audio players, videodisc players, regjistruesit videotape dhe
videotape players. Ky kontroll ngarkohet duke zgjedhur ne dritaren
Components Microsoft Multimedia Control.
Perdorimi kryesor per kete kontroll eshte:
Te administroje paisjet MCI te regjistrimit dhe ridegjimit
(playback). Kjo perfshin:
aftesine per te interpretuar (play) CD,
aftesine per te regjistruar dhe ridegjuar skedaret
WAV.
Kur vendoset ne nje forme, kontrolli multimedia eshte i ngjashem me buton
qe ne pergjithesi shikoni ne nje VCR:
Ju njiheni me butonat si Play, Rewind, Pause, etj.
Programim object-oriented Faqa 387
Programimi i kontrollit Multimedia:
Per te komanduar paisje multimedia te ndryshme, kontrolli multimedia
perdor nje grup komandash paisjesh – te pavaruara te nivelit te larte, te
njohura si komandat MCI (media control interface). Shembulli yne do te
demostroje se si ngjajne keto komanda.
Shembull i kontrollit Multimedia:
Do te perdorim kontrollin multimedia per te ndertuar nje audio CD player
te thjeshte. Vendosni nje kontroll multimedia ne forme. Shkruani kodin
me poshte ne ngjarjen Form_Load:
Private Sub Form_Load()
'Set initial properties
Form1.MMControl1.Notify = False
Form1.MMControl1.Wait = True
Form1.MMControl1.Shareable = False
Form1.MMControl1.DeviceType = "CDAudio"
'Open the device
Form1.MMControl1.Command = "Open"
End Sub
Ky kod inicializon paisjen ne kohen e ekzekutimit. Nqs nje audio CD
eshte e ngarkuar ne folene e CD(ne CD drive), butonat e duhur ne
kontrollin Multimedia jane enabled:
Provoni te luani nje CD me kete shembull dhe shikoni se si butonat
ndryshojne gjendje.
Programim object-oriented Faqa 388
Kontrolli Rich Textbox
Kontrolli rich textbox lejon perdoruesin te shkruaje dhe redaktoj tekst, duke
i dhene perdoruesit opsione me te avancuara formatimi se nje kontroll
tradicional textbox. Ju mund te perdorni font_e te ndryshme per seksione te
ndryshme teksti, te vendosni bullet ne paragraf etj. Ky kontroll ngarkohet
duke zgjedhur nga dritarja Components Microsoft Rich Textbox Control.
Perdorime te mundshme per kete kontrollit perfshijne:
Lximin dhe shfaqjen e skedareve te medhenje tekst.
Krijimin e nje text editori ne nje aplikacion.
Vetite, Ngjarjet dhe Metodat e kontrollit Rich Textbox
Pjesa me e madhe e vetive, ngjarjeve dhe metodave qe lidhen me nje text
box tradicional jane te perdorshme me nje rich text box. Dallimi kryesore
ndermjet ketyre dy kontrolleve eshte qe me nje rich textbox, suportohen
madhesi shkrimi, stile dhe ngjyra te shumta. Disa veti unike te rich
textbox jane:
FileName Mund te perdoret per te ngarkuar ne kontroll
permbajtjen e nje skedari .txt ose .rtf.
SelFontName Vendos llojin e shkrimit per tekstin e zgjedhur.
SelFontSize Vendos madhesine e shkrimit per tekstin e
zgjedhur.
SelFontColor Vendos ngjyren e shkrimit per tekstin e
zgjedhur.
Programim object-oriented Faqa 389
Disa metoda unike te rich textbox jane
LoadFile Hap nje skedar dhe ngarkon ne kontroll
permbajtjen e tij.
SaveFile Ruan permbajtjen e kontrollit ne nje skedar.
Shembull Rich Textbox:
Vendosni nje kontroll rich textbox ne forme.
Vendosni nje combo box ne forme (do perdoret per te shfaqur llojet e
shkrimit (fonts) te disponueshme per perdorim. Shkruani kodin me
poshte ne ngjarjen Form_Load:
Private Sub Form_Load()
Dim I As Integer
For I = 0 To Screen.FontCount - 1
Combo1.AddItem Screen.Fonts(I)
Next I
End Sub
Shkruani kodin me poshte ne ngjarjen Combo1_Click:
Private Sub Combo1_Click()
RichTextBox1.SelFontName = Combo1.Text
End Sub
Ekzekutoni aplikacionin. Shkruani ndonje tekst. Selektoni tekstin te cilit
doni ti ndryshoni llojin e shkrimit. Shkoni ne combo box dhe zgjidhni llojin
e shkrimit. Vini re se zona te ndryshme brenda text box mund te kene
lloje te ndryshme shkrimi:
Programim object-oriented Faqa 390
Programim object-oriented Faqa 391
Kontrolli Slider
Kontrolli slider eshte i ngjashem me nje scroll bar qe lejon mundesine per
te zgjedhur nje game vlerash si edhe nje vlere te vetme. Ky kontroll eshte
pjese e nje grupi kontrollesh qe ngarkohet duke zgjedhur ne dritaren
Components Microsoft Windows Common Controls.
Perdorime te mundshme per kete kontrollit perfshijne:
Te vendos vleren e nje pike ne nje diagrame.
Te zgjedhe nje game numrash qe i kalohen nje tabele.
Te ricaktoj madhesine e nje forme, fushe apo objekteve te
tjera grafike.
Vetite e kontrollit Slider:
Value Vlera aktuale e slider.
Min, Max Vendos limitin e poshtem dhe te siperm te
slider_it.
TickFrequency Percakton se sa shenja shfaqen slider.
TickStyle Percakton si dhe ku shfaqen shenjat.
SmallChange Sasia e vleres qe ndryshon kur perdoruesi
shtyp shigjeten e majte apo te djathte.
LargeChange Sasia e vleres qe ndryshon kur perdoruesi
shtyp slider_in ose shigjetat PgUp dhe PgDn.
Programim object-oriented Faqa 392
SelectRange Mundeson selektimin e nje game vlerash.
SelStart Vlera e pare e zgjedhur.
SelLength Numri i vlerave te zgjedhura.
Shembull per kontrollin Slider:
Do te ndertojme nje slider qe na lejon te zgjedhim nje game numrash
diku ndermjet vlerave ektreme nga 0 ne 100. Vendosim ne nje forme 2
labela dhe nje slider:
Vendosni vetite e slider SmallChange ne 1, LargeChange ne 10, Min
ne 0, Max ne 100, TickFrequency ne 10, dhe SelectRange ne True.
Shkruani kodin me poshte ne ngjarjen Slider1_MouseDown:
Private Sub Slider1_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
If Shift = 1 Then
Slider1.SelStart = Slider1.Value
Label1.Caption = Slider1.Value
Slider1.SelLength = 0
Label2.Caption = ""
End If
End Sub
Dhe kete kod ne ngjarjen Slider1_MouseUp:
Private Sub Slider1_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
Programim object-oriented Faqa 393
On Error Resume Next
If Shift = 1 Then
Slider1.SelLength = Slider1.Value - Slider1.SelStart
Label2.Caption = Slider1.Value
Else
Slider1.SelLength = 0
End If
End Sub
Ekzekutoni aplikacionin. Vendosni nje vlere fillestare per gamen e
zgjedhur duke zhvendosur slider ne piken qe deshironi. Me pas, klikoni nje
shenje ne slider ndersa mbani te shtypur celesin Shift dhe levizeni ate ne
vleren e siperme te deshiruar.
Programim object-oriented Faqa 394
Kontrolli Tabbed Dialog
Kontrolli tabbed dialog siguron nje menyre te thjeshte per te paraqitur
dialog_e (dritare me opsione) ose pamje me informacione te vecuara ne nje
forme te vetme duke perdorur te njejten nderfaqe sic kemi pare ne shume
aplikacione te Windows_it. Ky kontroll ngarkohet duke selektuar nga dritarja
Components Sheridan Tabbed Dialog Control.
Kontrolli tabbed dialog siguron nje grupe me tab_e, ku secili prej tyre ka
permbajtjen e vet (punon tamam si nje frame apo forme e vecante). Vetem
nje prej tab_eve mund te jete active ne nje moment kohe. Perdorimi i ketij
kontrolli eshte i thjeshte. Ndertoni permbajtjen e secilit tab si nje aplikacion
te vecante: shtoni kontrolle, vendosni veti dhe shkruani kode ashtu sic beni
ne ndonje aplikacion. Levizja nga nje permbajtje ne nje tjeter eshte e
thjeshte: thjesht klikoni ne tab_in perkates.
Shembull per kontrollin Tabbed Dialog:
Hapni nje aplikacion dhe vendosni ne forme nje kontrooll tabbed dialog:
Dizenjoni secilin tab me disa kontrolle dhe me pas ekzekutoni
aplikacionin. Vereni se si secili tab ka hapesiren e tij te punes.
Programim object-oriented Faqa 395
Kontrolli UpDown
Kontrolli updown eshte nje cift butonash shigjete te cilat perdoruesi mund
ti klikoje per te rritur apo zvogeluar nje vlere. Ai punon ne bashkepunim me
nje kontroll tjeter (buddy control) qe perdor vetine Value te kontrollit. Ky
kontroll eshte pjese e grupit te kontrolleve qe ngarkohen duke zgjedhur
Microsoft Windows Common Controls nga dritarja Components.
Vetite e kontrollit UpDown
Value Vlera aktuale e kontrollit.
Min, Max Vendos limitin e siperm dhe te poshtem te
kontrollit.
Increment Sasia qe ndryshohn vleren e kontrollit cdo here
qe klikohet nje shigjete.
Orientation Percakton nese shigjetat kane drejtim vertical
apo horizontal.
Ngjarjet e kontrollit UpDown
Change Thirret kur ndryshon vetia value.
UpClick Thirret kur klikohet shigjeta siper.
DownClick Thirret kur klikohet shigjeta poshte.
Programim object-oriented Faqa 396
Shembull per kontrollin UpDown
Le te ndertojme nje shembull qe na lejon te vendosim nje numer midis 1
dhe 25. Shtoni ne forme nje kontroll updown dhe nje label. Vendosni
vetite Min =1 dhe Max = 25 te kontrollit updown.
Forma do te jete e ngjashme si me poshte:
Shkruani kodin me poshte ne ngjarjen UpDown1_Change, dhe me pas
ekzekutojeni ate:
Private Sub UpDown1_Change()
Label1.Caption = UpDown1.Value
End Sub
Programim object-oriented Faqa 397
Kontrolli Toolbar
Ne ditet e sotme pothuajse gjithe aplikacionet ne Windows perdorin shirita
me vegla (toolbars). Nje toolbar siguron akses te shpejte te komandave te
menuve me te perdorshme ne nje aplikacion. Kontrolli toolbar eshte ne
vetvete nje 'mini-aplikacion’. Ai siguron gjithcka ju nevoitet per te dizenjuar
dhe per te vene ne perdorim nje toolbar ne aplikacionin tuaj. Ky kontroll
eshte pjese e grupit te kontrolleve qe ngarkohen duke klikuar Microsoft
Windows Common Controls ne dritaren Components.
Perdorime te mundshme te ketij kontrolli jane:
Siguron nje nderfaqe te qendrueshme ndermjet
aplikacioneve qe kane toolbar_e te njejte.
Pergjithesisht vendos funksione te perdorshme ne nje
hapesire me akses te thjesht.
Siguron nje nderfaqe intuitive dhe grafike per aplikacionit
tuaj.
Per te krijuar nje toolbar duhet te ndiqni disa hapa. Shtoni butona ne
nje koleksion Butonash - cdo buton mund te kete jo detyrimisht text
dhe/ose nje imazh, siguruar nga nje kontroll ImageList te
bashkangjitur (nje kontroll tjeter I perdoruesit). Butonat mund te
kene tooltips. Madje ne shume aplikacione te perparuara ju mund te
lejoni perdoruersit tuaj te pershtasin toolbar_in sipas deshirave te
tyre!
Pasi keni organizuar (ndertuar) toolbar_in, ju duhet te shkruani kodin
per ngjarjen ButtonClick. Indeksi i butonit te klikuar i kalon kesaj
Programim object-oriented Faqa 398
ngjarje si nje argument. Meqenese butonat na sigurojne akses te
shpejte te opsioneve neper menu te cilat jane tashme te koduara, kodi
ne kete ngjarje ne pergjithesi eshte thjesht nje thirrje e procedures
Click te elementit respektiv ne menu.
Shembull i kontrollit Toolbar Control
Do te shohim menyren me te thjeshte te perdorimit te toolbar –
duke ndertuar nje toolbar fiks formatimi (vetem imazh pictures
only) ne kohen e dizenjimit te forms. Do te ndertojme nje toolbar
me 5 butona: nje per krijimin e nje skedari te ri (new), nje per
hapjen e nje skedari (open), nje per te ruajtur skedarin (save), nje
per te printuar skedarin(print), dhe nje per ndihme (help). Shtoni
ne forme nje kontroll toolbar dhe nje imagelist. Klikoni me
butonin e djathte te mous_it mbi imagelist per te vendosur
imazhet qe do te perdoren. Duke perdorur tab_in Images, jepni 5
imazhet ne vazhdim: Imazh 1 - NEW.BMP, Imazh 2 - OPEN.BMP,
Imazh 3 - SAVE.BMP, Imazh 4 - PRINT.BMP, and Imazh 5 -
HELP.BMP
Pasi ta keni mbaruar, kontrolli do te duket si me poshte:
Programim object-oriented Faqa 399
Klikoni OK per te mbyllur dritaren. Tani klikoni me butonin e
djathte te mous_it mbi kontrollin toolbar. Shfaqet dialog box_i
Property Pages. Duke perdorur tab_in General, zgjidhni
kontrollin imagelist te sapo formuar. Tani, zgjidhni tab_in
Buttons per te percaktuar cdo buton:
Programim object-oriented Faqa 400
Duke klikuar Insert Button shtohet nje buton i ri ne toolbar. Per
cdo buton specifikoni te pakten vetine ToolTipText dhe , numrin e
Image. Vlerat e perdorura jane:
Index Teksti ne ToolTip Image
1 New File 1
2 Open File 2
3 Save File 3
4 Print File 4
5 -None- 0
6 Help me! 5
Butoni 5 (vendosni vetine Style = tbrPlaceholder) vendos nje hapesire
midis 4 butonave te pare dhe butonit Help. Pasi te mbaroni, forma do te
kete kete pamje:
Ruani dhe ekzekutoni aplikacionin. Theksojme se butonat thjesht do te
klikohen – nuk shkruajtem asnje kod (sic e permendem me pare, ne
pergjithesi kodi eshte thjesht thirrje e nje ngjarje ekzistuese e elementit te
menuse). Provoni se si shfaqen tool tip_et.
Shenim per Tooltip_et:
Programim object-oriented Faqa 401
Shume kontrolle ne Visual Basic mbajne tooltip_e per te informuar
perdoruesin mbi nje kontroll te vecante. Per te mundesuar kete opsion
thjesht vendosni ne vetine ToolTipText te kontrolleve te vecanta nje
tekst.
Programim object-oriented Faqa 402
Perdorimi i Windows Clipboard
Objekti Clipboard nuk ka veti dhe as ngjarje, por ka disa metoda qe ju
lejojne te transferoni te dhena ne/nga Windows clipboard. Disa metoda
transferojne tekst, disa transferojne grafika.
Nje metode qe punon me te dyja, dhe tekst dhe grafika eshte metoda Clear:
Clipboard.Clear Fshin permbajtjen e clipboard.
Per te zhvendosur informacion tekst ne/nga clipboard, perdorni metodat
SetText dhe GetText:
Clipboard.SetText Vendos tekst ne clipboard.
Clipboard.GetText Sjell tekst te ngarkuar ne clipboard.
Keto metoda perdoren shpesh per te realizuar veprimin e zhvendosjes (cut),
kopjimit (copy, dhe ngjitjes (paste).
Per te zhvendosur grafika ne/nga clipboard, perdorni metodat SetData dhe
GetData:
Clipboard.SetData Vendos nje imazh ne clipboard.
Clipboard.GetDataSjell nje imazh te ngarkuar ne clipboard.
Kur perdorni metodat e clipboard, keni nevoje te dini se cfare tipi te dhene
jeni duke transferuar (tekst apo grafike). Metoda qe jua lejon kete eshte
GetFormat :
Clipboard.GetFormat(datatype) Kthen True nqs permbajtja e
clipboard eshte tipi I specifikuar nga
datatype.
Programim object-oriented Faqa 403
Tipe te mundshme te dhenash jane:
Type Value Symbolic Constant
DDE conversation info HBF00 vbCFLink
Rich text format HBF01 vbCFRTF
Text 1 vbCFText
Bitmap 2 vbCFBitmap
Metafile 3 vbCFMetafile
Device-independent bitmap 8 vbCFDIB
Color palette 9 vbCFPalette
Programim object-oriented Faqa 404
Printing with Visual Basic
Nje aplikacion serioz ne Visual Basic mund te kete nevoje te perdori
printerin per te paisur perdoruesin me nje kopje fizike (hard copy) te
ndonje pune te bere apo rezultati te marre (tekst apo grafik). Printimi eshte
nje nga detyrat e programueshme me komplekse brenda Visual Basic.
Visual Basic perdor dy rruge kryesore per te printuar tekste dhe grafika:
Ju mund te krijoni output_in qe deshironi ne nje forme dhe me
pas te printoni gjithe formen duke perdorur metoden
PrintForm.
Ju mund te dergoni tekstin dhe grafikat ne objektin Printer dhe
me pas ti printoni ato duke perdorur metodat NewPage dhe
EndDoc.
Do te shohim se si te perdorim te dy rruget, duke keqyrur avantazhet dhe
disavantazhet e seciles. Te gjitha keto teknika perdorin printerin default
te sistemit (gjithashtu ju mund te zgjidhni nje printer ne Visual Basic, por
nuk do ta shohim ketu).
Metoda PrintForm dergon pixel-per-pixel ne printer imazhin e forms se
specifikuar. Per te printuar, fillimisht shfaqni formen sic deshironi dhe
nepermjet kodit therrisni komanden: PrintForm. Kjo komande do te
printoje gjithe formen, duke perdorur diemnsionet e zgjedhura te saj, madje
edhe nese pjese te forms nuk jane te dukshme ne ekran. Nqs forma permban
grafika, ato do te printohen vetem nese vetia AutoRedraw e forms eshte
True.
Metoda PrintForm eshte menyra me e thjeshte per te printuar nga nje
aplikacion. Por, rezultatet grafike mund te jene zhgenjyese sepse ato
Programim object-oriented Faqa 405
riprodhohen sipas rezolucionit te ekranit, jo te printerit dhe format e vogla
ngelen te vogla kur printohen.
Shembull i PrintForm:
Hapni nje aplikacion te ri. Vendosni ne forme nje image box. Percaktoni
madhesine e tij dhe vendosni vetine Stretch = True. Vendosni ne
vetine Picture ndonje imazh (preferohet metafiles, vendosni ju cfare
zgjidhni). Shtoni nje label. Shkruani ne ten je tekst te formatuar. Forma
do te duket si me poshte:
Shtoni ne ngjarjen Form_Click kodin:
Private Sub Form_Click()
PrintForm
End Sub
Ekzekutoni aplikacionin. Klikoni ne forme (jo imazhin apo label_in) dhe do te
printohet. Sic e shihni nuk eshte aspak e veshtire.
Duke perdorur objektin Printer per te printuar ne Visual Basic eshte me e
nderlikuar, por ne pergjithesi jep rezultate me te mira. Por te merrni keto
rezultate me te mira kerkohet pak kodim.
Objekti Printer eshte nje hapesire vizatimi e cila suporton disa metoda si:
Print, PSet, CurrentX, CurrentY, Line, PaintPicture (te perdorshme per
Programim object-oriented Faqa 406
te printuar permbajtjen e Picture boxes), dhe Circle, per te krijuar tekste dhe
grafika. Ju mund ti perdorni keto metoda sipas deshirave tuaja ne forme. Pasi
perfundoni se vendosuri informacion ne objektin Printer, perdorni metoden
EndDoc per te derguar output_in ne printer. Metoda NewPage ju
mundeson printimin e dokumentave me shume faqe.
Objekti Printer ka disa veti qe kontrollojne cilesine e printimit, madhesine e
faqes, numrin e kopjeve, shkallezimin, numrin e faqeve etj. Konsultohuni me
ndihmen on-line te Visual per informacione te metejshme.
Rruga e zakonshme per perdorimin e objektit Printer eshte te konsiderohet
cdo faqe e printuar sin je forme me sistemin e saj te koordinatave. Perdorni
kete system koordinatash dhe metodat e permendura me siper per te
vendosur tekst dhe grafika ne faqe. Pasi perfundoni, perdorni metoden
EndDoc (ose metoden NewPage nqs keni faqe te tjera). Ne kete pike, faqa
do te printohet. Veshtiresia kryesore ne perdorimin e objektit Printer eshte
te planifikoni se ku do te shkoje cdo gje. Ne pergjithesi perdoret metoda
Scale per te percaktuar fijen e letres standarte 8.5” me 11” me rritje 0.01”:
Printer.Scale (0, 0) - (850, 1100)
Me pas vendosni gjithcka ne faqen perkatese te ketyre koordinatave.
Shembulli ilustron perdorimin e disa prej ketyre teknikave. Konsultohuni me
material te tjera lidhur me Visual Basic per te mesuar me shume rreth
teknikave te avancuara te perintimit.
Shembull per objektin Printer:
Ne kete shembull, fillimisht do te percaktojme fijen e letres standarte. Me
pas do te perdorim metoden Line per te vizatuar nje kuti, metoden Circle
per te vizatuar nje rreth, dhe metoden Print per te ‘nxjerre’ nje tekst.
Programim object-oriented Faqa 407
Hapni nje aplikacion te ri. Ne forme nuk eshte e nevojshme te shtoni ndonje
kontroll – gjithe printimi kryhet ne procedure Form_Click.
Programim object-oriented Faqa 408
Private Sub Form_Click()
Printer.Scale (0, 0)-(850, 1100)
Printer.Line (100, 100)-(400, 300), , B
Printer.Circle (425, 550), 300
Printer.CurrentX = 100
Printer.CurrentY= 800
Printer.Print "This is some text."
Printer.EndDoc
End Sub
Le te themi pak per cdo rresht
kodi. Fillimisht, vendosim qe zona
e printimit (printing area) te jete
850 njesi e gjere dhe 1100 njesi e
gjate. Kjo na aleon te vendosim
elemente ne nje faqe standarte
brenda 0.01 inches. Me pas,
vizatojme nje kuti, duke filluar 1
inch nga e majta dhe 1 inch nga
lart, qe eshte 3 inches i gjere dhe
2 inches i larte. Me pas, vizatohet
nje rreth me qender ne mes te faqes, me rreze prej 3 inches. Ne fund,
printohet nje rresht me tekst afer fundit te faqes. Printimin e ben metoda
EndDoc. Faqa e printuar tregohet ne te djathte.
Ekzekutoni aplikacionin. Klikoni formen per te filluar printimin.
Programim object-oriented Faqa 409
Aplikacionet ne Visual Basic me Shume Forma
Gjithe aplikacionet e zhvilluara deri tani perdorin nje forme te vetme. Ne
realitet, pjesa me e madhe e aplikacioneve ne Visual Basic perdorin shume
forma (multiple forms). Dritarja About qe shoqeron pjesen me te madhe
te aplikacioneve eshte nje shembull i thjeshte i perdorimit te nje forme te
dyte ne nje aplikacion. Ne vazhdim do te shohim se si te administrojme
shume forma ne projektet tona.
Per te shtuar nje forme ne nje aplikacion, klikoni butonin New Form ne
toolbar ose zgjidhni Form ne menune Insert. Cdo forme dizenjohet duke
perdorur saktesisht te njejten menyre veprimi sic kemi bere deri tani:
vizatojme kontrollet, percaktojme vetite dhe shkruajme kodin. Shfaqja e
formave te ndryshme manovrohet nga kodi qe ju shkruani. Ju duhet te
vendosni kur dhe si forma te vecanta te shfaqen. Perdoruesi gjithmone
bashkevepron me formen qe eshte ‘aktive’.
Vendimi i pare qe duhet te merrni eshte te percaktoni se cila do te jete forma
e fillimit (startup form). Kjo eshte forma qe shfaqet kur fillon aplikacioni.
Forma e fillimit percaktohet duke perdorur dritaren Project Properties ne
menune Project:
Programim object-oriented Faqa 410
Sic e permendem, forma e fillimit ngarkohet automatikisht kur ekzekutohet
aplikacioni. Nese doni qe te shfaqet nje forme tjeter, ju duhet te shkruani
kod per ngarkimin dhe shfaqjen e saj. Ne menyre te ngjashme, kur doni te
fshihni nje forme, ju duhet te shkruani kod per cngarkimin dhe fshehjen e saj.
Ky administrim i formes kryhet duke perdorur disa keywords:
Keyword Detyra
Load Ngarkon nje forme ne kujtese, por nuk e shfaq ate.
Show vbModeless Ngarkon (nese tashme nuk eshte ngarkuar) dhe
shfaq nje modeless forme (standarte Show form
style).
Show vbModal Ngarkon (if nese tashme nuk eshte ngarkuar) dhe
shfaq nje modal forme.
Hide Vendos vetine Visible te forms = False. Forma
qendron ne kujtese.
Unload Fsheh nje formed he e fshin ate nga kujtesa.
Programim object-oriented Faqa 411
Startup Form
Mund te largohemi nga nje modeless form per te shkuar ne forma te
tjera. Nderkohe nje modal form duhet te mbyllet perpara se te shkojme
ne forma te tjera. Forma e fillimit eshte form modeless.
Examples
Load Form1 ‘ Loads Form1 into memory, but does not display it
Form1.Show ‘ Loads (if needed) and shows Form1 as modeless
Form1.Show vbModal ‘ Loads (if needed) and shows Form1 as modal.
Form1.Hide ‘ Sets Form1’s Visible property to False
Hide ‘ Hides the current form
Unload Form1 ‘ Unloads Form1 from memory and hides it.
Fshehja e nje forme e lejon ate qe te rrithiret shpejt nese eshte e nevojshme.
Hiding a form allows it to be recalled quickly, if needed. Hiding a form
retains any data attached to it, including property values, print output, and
dynamically created controls. You can still refer to properties of a hidden
form. Unload a form if it is not needed any longer, or if memory space is
limited.
If you want to speed up display of forms and memory is not a problem, it is a
good idea to Load all forms when your application first starts. That way,
they are in memory and available for fast recall.
Multiple Form Example:
Programim object-oriented Faqa 412
Start a new application. Put two command buttons on the form (Form1).
Set one’s Caption to Display Form2 and the other’s Caption to Display
Form3. The form will look like this:
Attach this code to the two command buttons Click events.
Private Sub Command1_Click()
Form2.Show vbModeless
End Sub
Private Sub Command2_Click()
Form3.Show vbModal
End Sub
Add a second form to the application (Form2). This form will be
modeless. Place a command button on the form. Set its Caption to
Hide Form.
Programim object-oriented Faqa 413
Attach this code to the button’s Click event.
Private Sub Command1_Click()
Form2.Hide
Form1.Show
End Sub
Add a third form to the application (Form3). This form will be modal.
Place a command button on the form. Set its Caption to Hide Form.
Attach this code to the button’s Click event.
Private Sub Command1_Click()
Form3.Hide
Form1.Show
End Sub
Programim object-oriented Faqa 414
Make sure Form1 is the startup form (check the Project Properties
window under the Project menu). Run the application. Note the
difference between modal (Form3) and modeless (Form2) forms.
Programim object-oriented Faqa 415
Visual Basic Multiple Document Interface (MDI)
In the previous section, we looked at using multiple forms in a Visual Basic
application. Visual Basic actually provides a system for maintaining multiple-
form applications, known as the Multiple Document Interface (MDI). MDI
allows you to maintain multiple forms within a single container form.
Examples of MDI applications are Word, Excel, and the Windows Explorer
program.
An MDI application allows the user to display many forms at the same time.
The container window is called the parent form, while the individual forms
within the parent are the child forms. Both parent and child forms are
modeless, meaning you can leave one window to move to another. An
application can have only one parent form. Creating an MDI application is a
two-step process. You first create the MDI form (choose Add MDI Form
from Project menu) and define its menu structure. Next, you design each of
the application’s child forms (set MDIChild property to True).
Design-Time Features of MDI Child Forms:
At design time, child forms are not restricted to the area inside the parent
form. You can add controls, set properties, write code, and design the
features of child forms anywhere on the desktop.
You can determine whether a form is a child by examining its MDIChild
property, or by examining the project window. The project window uses
special icons to distinguish standard forms, MDI child forms, and MDI
parent forms:
Programim object-oriented Faqa 416
Run-Time Features of MDI Child Forms
At run-time, the parent and child forms take on special characteristics and
abilities. Some of these are:
1. At run-time all child forms are displayed within the parent form’s
internal area. The user can move and size child forms like any other
form, but they must stay in this internal area.
2. When a child is minimized, its icon appears on the MDI parent form
instead of the user’s desktop. When the parent form is minimized, the
entire application is represented by a single icon. When restored, all
forms are redisplayed as they were.
3. When a child form is maximized, its caption is combined with the
parent form’s caption and displayed in the parent title bar.
4. By setting the AutoShowChildren property, you can display child
forms automatically when forms are loaded (True), or load child forms
as hidden (False).
5. The active child form’s menus (if any) are displayed on the parent
form’s menu bar, not the child form.
6. New child forms can be created at run-time using a special form of the
Dim statement and the Show statement (the example illustrates this
process).
7. The parent form’s ActiveForm property indicates which child form is
currently active. The ActiveControl property indicates which control
on the active child form has focus.
Programim object-oriented Faqa 417
Parent form
Standard form
Child form
8. The Arrange command can be used to determine how the child forms
and their icons (if closed) are displayed.
Programim object-oriented Faqa 418
The syntax is:
Arrange style
where style can take on these values:
Style Symbolic Constant Effect
0 vbCascade Cascade all nonminimized MDI child
forms.
1 vbTileHorizontal Horizontally tile all nonminimized MDI
child forms.
2 vbTileVertical Vertically tile all nonminimized MDI
child forms.
3 vbArrangeIcons Arrange icons for minimized MDI child
forms.
Multiple-Document Application (MDI) Example:
We’ll create an MDI application which uses a simple, text box-based, editor as
the child application. There are a lot of steps, even for a simple example. Start
a new application. Create a parent form by selecting MDI Form from the Insert
menu. At this point, the project will contain an MDI parent form (MDIForm1)
and a standard form (Form1) which we will use as a child form. Make MDIForm1
the startup form. We work with the parent form first:
1. Set the following properties:
Caption MDI Example
Name frmParent
WindowState 2-Maximized
Programim object-oriented Faqa 419
Set up the following menu structure:
Caption Name Indented
&File mnuFile No
&New mnuFileNew Yes
&Arrange mnuArrange No
&Cascade mnuArrangeItem Yes Index = 0
&Horizontal Tile mnuArrangeItem Yes Index = 1
&Vertical Tile mnuArrangeItem Yes Index = 2
&Arrange Icons mnuArrangeItem Yes Index = 3
2. Attach this code to the mnuFileNew_Click procedure. This code
creates new child forms (named frmChild - developed next).
Private Sub mnuFileNew_Click()
Dim NewDoc As New frmChild
NewDoc.Show
End Sub
3. Attach this code to the mnuArrangeItem_Click procedure. This
establishes how child forms are displayed.
Private Sub mnuArrangeItem_Click(Index As Integer)
Arrange Index
End Sub
Programim object-oriented Faqa 420
Now, we’ll work with Form1 which will hold the child application:
5. Draw a text box on the form. Set the following properties for the form
and the text box:
Form1:
Caption Child Form
MDIChild True
Name frmChild
Visible False
Text1:
Left 0
MultiLine True
ScrollBars 2-Vertical
Text [Blank]
Top 0
My form resembles this:
6. Attach this code to the Form_Resize procedure. This insures that
whenever a child window is resized, the text box fills up the entire
window.
Programim object-oriented Faqa 421
Private Sub Form_Resize()
Text1.Height = ScaleHeight
Text1.Width = ScaleWidth
End Sub
Run the application. Create new forms by selecting New from the File
menu. Try resizing forms, maximizing forms (notice how the parent form
title bar changes), minimizing forms, closing forms. Try all the Arrange
menu options.
Programim object-oriented Faqa 422
Creating a Help File
During this course, we’ve made extensive use of the Visual Basic on-line help
system. In fact, one of the major advances in software in the past few years has
been improvements in such interactive help. Adding a help file to your Visual
Basic application will give it real polish, as well as making it easier to use.
Your help file will contain text and graphics information needed to be able to run
your application. The help file will be displayed by the built-in Windows help utility
that you use with every Windows application, hence all functions available with that
utility are available with your help system. For example, each file can contain one
or more topics that your user can select by clicking a hot spot, using a keyword
search, or browsing through text. And, it’s easy for your user to print any or all
help topics.
Creating a complete help file is a major task and sometimes takes as much time as
creating the application itself! Because of this, we will only skim over the steps
involved, generate a simple example, and provide guidance for further reference.
There are five major steps involved in building your own help file:
1. Create your application and develop an outline of help system
topics.
2. Create the Help Text File (or Topic File) in RTF format.
3. Create the Help Project File (HPJ).
4. Compile the Help File using the Help Compiler and Project File.
5. Attach the Help File to your Visual Basic application.
Step 1 is application-dependent. We’ll look briefly at the last four steps here.
More complete details, including formatting and file structure requirements, are
available in many Visual Basic references.
Programim object-oriented Faqa 423
Creating a Help Text File
To create a Help Text File, you need to use a word processor capable of saving
documents in rich-text format (RTF). Word and WordPerfect do admirable
jobs. You must also be familiar with text formatting procedures such as
underlining, double-underlining, typing hidden text, and using footnotes. This
formatting is used to delineate different parts of the help file. You should make
sure all formatting options are visible when creating the Help Text File.
The Help Text File is basically a cryptically encoded list of hypertext jumps
(jump phrases) and context strings. These are items that allow navigation
through the topics in your help file. Some general rules of Help Text Files:
Topics are separated by hard page breaks.
Each topic must have a unique context string.
Each topic can have a title.
A topic can have many keywords attached to it to enable quick
access utilizing a search facility.
Topics can have build-tag indicators and can be assigned a browse
sequence.
Jumps can be to another secondary window or to another file.
Once completed, your Help Text File must be saved as an RTF file.
Help Text File Example:
We’ll create a very simple help text file with three topics. I used Word 6.0 in this
example. Create a document with the following structure and footnotes:
Programim object-oriented Faqa 424
Some things to note: Topic1 and Topic3 (hypertext jumps) are double-
underlined to indicate clickable jumps to topics. Topic2 is single-underlined to
indicate a jump to a pop-up topic. The words HID_TOPIC1, HID_TOPIC2, and
HID_TOPIC3 (context strings) are formatted as hidden text. Note page breaks
separate each section. Do not put a page break at the end of the file.
Also, note the use of footnotes. The # footnote is used to specify a Help context
ID, the $ provides Topic Titles for searching, and K yields search keywords. The
footnotes for this example are:
Programim object-oriented Faqa 425
When done, save this file as SIMPLE.RTF (Rich Text Format).
Creating the Help Project File:
The Help Project File contains the information required by the Help Compiler
to create the Help file. The file is created using any text editor and must be
saved as unformatted text (ASCII). The file extension is HPJ.
The Help Project File can contain up to nine sections, each of which supplies
information about the source file to compile. Sections names are placed within
square brackets [ ]. Semicolons are used to indicate a comment. Sections can
be in any order. The sections are:
[OPTIONS] Specifies options for build (optional).
[FILES] Specifies Help Text Files (RTF) (required).
[BUILDTAGS] Specifies any build tags (optional).
[CONFIG] Author defined menus, macros, etc. (optional)
Programim object-oriented Faqa 426
[BITMAPS] Specifies any bitmaps needed for build.
[ALIAS] Can be used to specify context strings to topics (optional).
[MAP] Associates context strings with numbers. Used with context-
sensitive help (optional).
[WINDOWS] Defines primary and secondary windows (required only if
secondary windows used).
[BAGGAGE] Lists files to be included in HLP file.
Help Project File Example:
For our simple example, the Help Project File is equally simple:
[OPTIONS]
CONTENTS=HID_CONTENTS
TITLE=SIMPLE Application Help
[FILES]
SIMPLE.RTF
This file specifies the context ID of the Table of Contents screen and the name of
the RTF file that contains the help text. Save this file as SIMPLE.HPJ (in Text, or
ASCII format).
Programim object-oriented Faqa 427
Compiling the Help File
This is the easiest step. The help compiler is located in the c:\Program Files\
DevStudio\vb\hc directory and is the program hc.exe. Your file is compiled within
the DOS window. Once in that window, move to the directory containing your HPJ
file and type:
c:\Program Files\DevStudio\vb\hc\hc filename.HPJ
where filename is your Help Project File. This process generates a binary help
resource file and may take a long time to complete. Any errors are probably due to
problems in the RTF file(s). The created file has the same name as your Help
Project File with an HLP extension.
Help File Example:
To compile the example, at a DOS prompt, type:
c:\Program Files\DevStudio\vb\hc\hc SIMPLE.HPJ
The help file SIMPLE.HLP will be created (if no errors occur) and saved in the same
directory as your HPJ file.
Attaching the Help File
The final step is to attach the compiled help file to your application. As a first
step, open the Project Properties window under the Project menu. Under
Help File, select the name of your HLP file by clicking the ellipsis (...). This ties
the help file to the application, enabling the user to press F1 for help.
You can also add a Help item somewhere in your menu structure that invokes
help via its Click event. If you do this, you must write code to invoke the help
file. The code involves a call to the Windows API function, WinHelp. But, after
last class, we’re not daunted by such functions, are we? First, we need the
function declaration (from the API Text Viewer):
Declare Function WinHelp Lib "user32" Alias "WinHelpA" (ByVal hwnd
As Long, ByVal lpHelpFile As String, ByVal wCommand As Long, ByVal
dwData As Long) As Long
Programim object-oriented Faqa 428
We also need a constant (also from the API Text Viewer):
Const HELP_INDEX = &H3 ' Display index
This constant will declare the Help files index page upon invocation of WinHelp.
There are other constants that can be used with WinHelp - this is just a simple
example. The Declare statement and constant definitions usually go in the
general declarations area of a code module and made Public. If you only have
one form in your application, then put these statements in the general
declarations area of your form (and declare them Private). Once everything is
in-place, to invoke the Help file from code, use the function call:
Dim R As Long
.
.
R = WinHelp(startupform.hWnd, filename.HLP, HELP_INDEX, CLng(0))
where startupform is the name of your application main form and filename is the
help file name, including path information.
Help File Example:
We can now try our example help file in a Visual Basic application. We’ll only
use the F1 option here. Start a new application. Bring up the Project
Properties window via the Project menu. Select the correct Help File by
clicking the ellipsis and finding your newly created file. Click OK. Now, run your
application (I know there’s nothing in the application, but that’s all right). Once,
it’s running press F1. This Help screen should appear:
Programim object-oriented Faqa 429
Move the mouse cursor to Topic1 and notice the cursor changes to a hand.
Click there and the corresponding Topic 1 screen appears:
The HID_TOPIC1 text in the Table of Contents screen links to the corresponding
context ID (the # footnote) in the topic page. This link is a jump. The link to
Topic 2 is a pop-up jump, try it and you’ll see.
Go back to the Table of Contents screen and click the Search button. A dialog
box displaying the help file’s list of keywords appears. In our example, the three
topics all have the same keyword (the K footnotes), SIMPLE Topics. When you
double-click on this keyword, you see all the associated topic titles (the $
footnotes):
Programim object-oriented Faqa 430
You can now select your topic of choice.
More Help File Topics
After all this work, you will still only have a simple help file, nothing that rivals
those seen in most applications. To improve your help system, you need to add
some more stuff. Information on these advanced help topics is found in many
Visual Basic references.
A big feature of help systems is context-sensitive help. With this, you place the
cursor on or in something your interested in knowing about and press F1. A Help
topic, if one exists, shows up. The application is smart enough to know what you
want help with. Graphics always spiff up a help system. Help systems use a
special type of graphics called hypergraphics. Lastly, Help macros add
functionality to your help system. There are over 50 macro routines built into the
DLL WinHelp application.
If, after seeing the rather daunting tasks involved in creating a help system, you
don’t want to tackle the job, take heart. There are several third party software
packages that assist in help system authoring and development. Look at computer
magazine advertisements (especially the Visual Basic Programmer’s Journal) for
potential leads.
Programim object-oriented Faqa 431
Class Summary
That’s all I know about Visual Basic. You should now have a good breadth of
knowledge concerning the Visual Basic environment and language. This breadth
should serve as a springboard into learning more as you develop your own
applications. Feel free to contact me, if you think I can answer any questions
you might have.
Where do you go from here? With Visual Basic 6.0, you can extend your
knowledge to write Web-based applications, develop massive database front-
ends using Visual Basic’s powerful database tools and techniques, and even
develop your own ActiveX (custom) controls. Other classes cover such topics.
Programim object-oriented Faqa 432
Shembulli i fundit
Programim object-oriented Faqa 433
Exercise 10
The Ultimate Application
Design an application in Visual Basic that everyone on the planet wants to buy.
Draw objects, assign properties, attach code. Thoroughly debug and test your
application. Create a distribution disk. Find a distributor or distribute it yourself
through your newly created company. Become fabulously wealthy. Remember
those who made it all possible by rewarding them with jobs and stock options.
My Solution:
Still working on it ...
Programim object-oriented Faqa 434
10. Appendix I. Simbolet e Kontsanteve ne Visual Basic
Alignment Constants
Align Property
Constant Value Description
vbAlignNone 0 Size and location set at design time or in code.
vbAlignTop 1 Picture box at top of form.
vbAlignBottom 2 Picture box at bottom of form.
vbAlignLeft 3 Picture box at left of form.
vbAlignRight 4 Picture box at right of form.
Alignment Property
Constant Value Description
vbLeftJustify 0 Left align.
vbRightJustify 1 Right align.
vbCenter 2 Center.
Border Property Constants
Programim object-oriented Faqa 435
BorderStyle Property (Form)
Constant Value Description
vbBSNone 0 No border.
vbFixedSingle 1 Fixed single.
vbSizable 2 Sizable (forms only)
vbFixedDouble 3 Fixed double (forms only)
BorderStyle Property (Shape and Line)
Constant Value Description
vbTransparent 0 Transparent.
vbBSSolid 1 Solid.
vbBSDash 2 Dash.
vbBSDot 3 Dot.
vbBSDashDot 4 Dash-dot.
vbBSDashDotDot 5 Dash-dot-dot.
vbBSInsideSolid 6 Inside solid.
Clipboard Object Constants
Constant Value Description
vbCFLink 0xBF00 DDE conversation information.
vbCFRTF 0xBF01 Rich Text Format (.RTF file)
vbCFText 1 Text (.TXT file)
vbCFBitmap 2 Bitmap (.BMP file)
Programim object-oriented Faqa 436
vbCFMetafile 3 Metafile (.WMF file)
vbCFDIB 8 Device-independent bitmap.
vbCFPalette 9 Color palette.
Color Constants
Colors
Constant Value Description
vbBlack 0x0 Black.
vbRed 0xFF Red.
vbGreen 0xFF00 Green.
vbYellow 0xFFFF Yellow.
vbBlue 0xFF0000 Blue.
vbMagenta 0xFF00FF Magenta.
vbCyan 0xFFFF00 Cyan.
vbWhite 0xFFFFFF White.
System Colors
Constant Value Description
vbScrollBars 0x80000000 Scroll bar color.
vbDesktop 0x80000001 Desktop color.
vbActiveTitleBar 0x80000002 Color of the title bar for the active window.
vbInactiveTitleBar 0x80000003 Color of the title bar for the inactive window.
Programim object-oriented Faqa 437
vbMenuBar 0x80000004 Menu background color.
vbWindowBackground 0x80000005 Window background color.
vbWindowFrame 0x80000006 Window frame color.
vbMenuText 0x80000007 Color of text on menus.
vbWindowText 0x80000008 Color of text in windows.
vbTitleBarText 0x80000009 Color of text in caption, size box, and scroll arrow.
vbActiveBorder 0x8000000A Border color of active window.
vbInactiveBorder 0x8000000B Border color of inactive window.
vbApplicationWorkspace 0x8000000C Background color of multiple-document interface (MDI)
System Colors (continued)
Constant Value Description
vbHighlight 0x8000000D Background color of items selected in a control.
vbHighlightText 0x8000000E Text color of items selected in a control.
vbButtonFace 0x8000000F Color of shading on the face of command buttons.
vbButtonShadow 0x80000010 Color of shading on the edge of command buttons.
vbGrayText 0x80000011 Grayed (disabled)
vbButtonText 0x80000012 Text color on push buttons.
vbInactiveCaptionText 0x80000013 Color of text in an inactive caption.
vb3DHighlight 0x80000014 Highlight color for 3D display elements.
Programim object-oriented Faqa 438
vb3DDKShadow 0x80000015 Darkest shadow color for 3D display elements.
vb3DLight 0x80000016 Second lightest of the 3D colors after vb3DHighlight.
vbInfoText 0x80000017 Color of text in ToolTips.
vbInfoBackground 0x80000018 Background color of ToolTips.
Control Constants
ComboBox Control
Constant Value Description
vbComboDropdown 0 Dropdown Combo.
vbComboSimple 1 Simple Combo.
vbComboDropdownList 2 Dropdown List.
ListBox Control
Constant Value Description
vbMultiSelectNone 0 None.
vbMultiSelectSimple 1 Simple.
vbMultiSelectExtended 2 Extended.
ScrollBar Control
Constant Value Description
vbSBNone 0 None.
vbHorizontal 1 Horizontal.
Programim object-oriented Faqa 439
vbVertical 2 Vertical.
vbBoth 3 Both.
Shape Control
Constant Value Description
vbShapeRectangle 0 Rectangle.
vbShapeSquare 1 Square.
vbShapeOval 2 Oval.
vbShapeCircle 3 Circle.
vbShapeRoundedRectangle 4 Rounded rectangle.
vbShapeRoundedSquare 5 Rounded square.
Data Control Constants
Error Event Constants
Constant Value Description
vbDataErrContinue 0 Continue.
vbDataErrDisplay 1 (Default)
EditMode Property Constants
Constant Value Description
vbDataEditNone 0 No editing operation in progress.
vbDataEditMode 1 Edit method invoked; current record in copy buffer.
Programim object-oriented Faqa 440
vbDataEditAdd 2 AddNew method invoked; current record hasn't been saved.
Options Property Constants
Constant Value Description
vbDataDenyWrite 1 Other users can't change records in recordset.
vbDataDenyRead 2 Other users can't read records in recordset.
vbDataReadOnly 4 No user can change records in recordset.
vbDataAppendOnly 8 New records can be added to the recordset, but existing records can't be read.
vbDataInconsistent 16 Updates can apply to all fields of the recordset.
vbDataConsistent 32 Updates apply only to those fields that will not affect other records in the recordset.
vbDataSQLPassThrough 64 Sends an SQL statement to an ODBC database.
Validate Event Action Constants
Constant Value Description
vbDataActionCancel 0 Cancel the operation when the Sub exits.
vbDataActionMoveFirst 1 MoveFirst method.
vbDataActionMovePrevious 2 MovePrevious method.
Programim object-oriented Faqa 441
vbDataActionMoveNext 3 MoveNext method.
vbDataActionMoveLast 4 MoveLast method.
vbDataActionAddNew 5 AddNew method.
vbDataActionUpdate 6 Update operation (not UpdateRecord)
vbDataActionDelete 7 Delete method.
vbDataActionFind 8 Find method.
vbDataActionBookmark 9 The Bookmark property is set.
vbDataActionClose 10 Close method.
vbDataActionUnload 11 The form is being unloaded.
Beginning-of-File Constants
Constant Value Description
vbMoveFirst 0 Move to first record.
vbBOF 1 Move to beginning of file.
End-of-File Constants
Constant Value Description
vbMoveLast 0 Move to last record.
vbEOF 1 Move to end of file.
vbAddNew 2 Add new record to end of file.
Recordset-Type Constants
Constant Value Description
vbRSTypeTable 0 Table-type recordset.
Programim object-oriented Faqa 442
vbRSTypeDynaset 1 Dynaset-type recordset.
vbRSTypeSnapShot 2 Snapshot-type recordset.
Date Constants
firstdayofweek Argument Values
Constant Value Description
vbUseSystem 0 Use NLS API setting.
vbSunday 1 Sunday
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday
firstweekofyear Argument Values
Constant Value Description
vbUseSystem 0 Use application setting if one exists; otherwise use NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default)
vbFirstFourDays 2 Start with the first week that has at least four days in the new year.
Programim object-oriented Faqa 443
vbFirstFullWeek 3 Start with the first full week of the year.
Return Values
Constant Value Description
vbSunday 1 Sunday
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday
DBGrid Control Constants
Alignment Constants
Constant Value Description
dbgLeft 0 Left.
dbgRight 1 Right.
dbgCenter 2 Center.
dbgGeneral 3 General.
BorderStyle Constants
Constant Value Description
Programim object-oriented Faqa 444
dbgNone 0 None.
dbgFixedSingle 1 FixedSingle.
DataMode Constants
Constant Value Description
dbgBound 0 Bound.
dbgUnbound 1 Unbound.
DividerStyle Constants
Constant Value Description
dbgNoDividers 0 NoDividers.
dbgBlackLine 1 BlackLine.
dbgDarkGrayLine 2 DarkGrayLine.
dbgRaised 3 Raised.
dbgInset 4 Inset.
dbgUseForeColor 5 UseForeColor.
RowDividerStyle Constants
Constant Value Description
dbgNoDividers 0 NoDividers.
dbgBlackLine 1 BlackLine.
dbgDarkGrayLine 2 DarkGrayLine.
dbgRaised 3 Raised.
dbgInset 4 Inset.
dbgUseForeColor 5 UseForeColor.
Programim object-oriented Faqa 445
Scroll Bar Constants
Constant Value Description
dbgNone 0 None.
dbgHorizontal 1 Horizontal.
dbgVertical 2 Vertical.
dbgBoth 3 Both.
dbgAutomatic 4 Automatic.
Programim object-oriented Faqa 446
DDE Constants
linkerr (LinkError Event)
Constant Value Description
vbWrongFormat 1 Another application requested data in wrong format.
vbDDESourceClosed 6 Destination application attempted to continue after source closed.
vbTooManyLinks 7 All source links are in use.
vbDataTransferFailed 8 Failure to update data in destination.
LinkMode Property (Forms and Controls)
Constant Value Description
vbLinkNone 0 None.
vbLinkSource 1 Source (forms only)
vbLinkAutomatic 1 Automatic (controls only)
vbLinkManual 2 Manual (controls only)
vbLinkNotify 3 Notify (controls only)
Dir, GetAttr, and SetAttr Constants
Constant Value Description
vbNormal 0 Normal (default for Dir and SetAttr)
Programim object-oriented Faqa 447
vbReadOnly 1 Read-only.
vbHidden 2 Hidden.
vbSystem 4 System file.
vbVolume 8 Volume label.
vbDirectory 16 Directory.
vbArchive 32 File has changed since last backup.
Drag-and-Drop Constants
DragOver Event
Constant Value Description
vbEnter 0 Source control dragged into target.
vbLeave 1 Source control dragged out of target.
vbOver 2 Source control dragged from one position in target to another.
Drag Method (Controls)
Constant Value Description
vbCancel 0 Cancel drag operation.
vbBeginDrag 1 Begin dragging control.
vbEndDrag 2 Drop control.
DragMode Property
Programim object-oriented Faqa 448
Constant Value Description
vbManual 0 Manual.
vbAutomatic 1 Automatic.
Drawing Constants
DrawMode Property
Constant Value Description
vbBlackness 1 Black.
vbNotMergePen 2 Not Merge pen.
vbMaskNotPen 3 Mask Not pen.
vbNotCopyPen 4 Not Copy pen.
vbMaskPenNot 5 Mask pen Not.
vbInvert 6 Invert.
vbXorPen 7 Xor pen.
vbNotMaskPen 8 Not Mask pen.
vbMaskPen 9 Mask pen.
vbNotXorPen 10 Not Xor pen.
vbNop 11 No operation; output remains unchanged.
vbMergeNotPen 12 Merge Not pen.
vbCopyPen 13 Copy pen.
vbMergePenNot 14 Merge pen Not.
vbMergePen 15 Merge pen.
Programim object-oriented Faqa 449
vbWhiteness 16 White.
DrawStyle Property
Constant Value Description
vbSolid 0 Solid.
vbDash 1 Dash.
vbDot 2 Dot.
vbDashDot 3 Dash-dot.
vbDashDotDot 4 Dash-dot-dot.
vbInvisible 5 Invisible.
vbInsideSolid 6 Inside solid.
Form Constants
Show Parameters
Constant Value Description
vbModal 1 Modal form.
vbModeless 0 Modeless form.
Arrange Method for MDI Forms
Constant Value Description
vbCascade 0 Cascade all nonminimized MDI child forms.
Programim object-oriented Faqa 450
vbTileHorizontal 1 Horizontally tile all nonminimized MDI child forms.
vbTileVertical 2 Vertically tile all nonminimized MDI child forms.
vbArrangeIcons 3 Arrange icons for minimized MDI child forms.
WindowState Property
Constant Value Description
vbNormal 0 Normal.
vbMinimized 1 Minimized.
vbMaximized 2 Maximized.
Graphics Constants
FillStyle Property
Constant Value Description
vbFSSolid 0 Solid.
vbFSTransparent 1 Transparent.
vbHorizontalLine 2 Horizontal line.
vbVerticalLine 3 Vertical line.
vbUpwardDiagonal 4 Upward diagonal.
vbDownwardDiagonal 5 Downward diagonal.
vbCross 6 Cross.
vbDiagonalCross 7 Diagonal cross.
Programim object-oriented Faqa 451
ScaleMode Property
Constant Value Description
vbUser 0 User.
vbTwips 1 Twips.
vbPoints 2 Points.
vbPixels 3 Pixels.
vbCharacters 4 Characters.
vbInches 5 Inches.
vbMillimeters 6 Millimeters.
vbCentimeters 7 Centimeters.
Grid Control Constants
ColAlignment, FixedAlignment Properties
Constant Value Description
grdAlignCenter 2 Center data in column.
grdAlignLeft 0 Left-align data in column.
grdAlignRight 1 Right-align data in column.
FillStyle Property
Constant Value Description
grdSingle 0 Changing Text property setting affects only active cell.
Programim object-oriented Faqa 452
grdRepeat 1 Changing Text property setting affects all selected cells.
Programim object-oriented Faqa 453
Help Constants
Constant Value Description
cdlHelpContext 0x1 Displays Help for a particular topic.
cdlHelpQuit 0x2 Notifies the Help application that the specified Help file is no longer in use.
cdlHelpIndex 0x3 Displays the index of the specified Help file.
cdlHelpContents 0x3 Displays the contents topic in the current Help file.
cdlHelpHelpOnHelp 0x4 Displays Help for using the Help application itself.
cdlHelpSetIndex 0x5 Sets the current index for multi-index Help.
cdlHelpSetContents 0x5 Designates a specific topic as the contents topic.
cdlHelpContextPopup 0x8 Displays a topic identified by a context number.
cdlHelpForceFile 0x9 Creates a Help file that displays text in only one font.
cdlHelpKey 0x101 Displays Help for a particular keyword.
cdlHelpCommandHelp 0x102 Displays Help for a particular command.
cdlHelpPartialKey 0x105 Calls the search engine in Windows Help.
Programim object-oriented Faqa 454
Key Code Constants
Key Codes
Constant Value Description
vbKeyLButton 0x1 Left mouse button.
vbKeyRButton 0x2 Right mouse button.
vbKeyCancel 0x3 CANCEL key.
vbKeyMButton 0x4 Middle mouse button.
vbKeyBack 0x8 BACKSPACE key.
vbKeyTab 0x9 TAB key.
vbKeyClear 0xC CLEAR key.
vbKeyReturn 0xD ENTER key.
vbKeyShift 0x10 SHIFT key.
vbKeyControl 0x11 CTRL key.
vbKeyMenu 0x12 MENU key.
Key Codes (continued)
Constant Value Description
vbKeyPause 0x13 PAUSE key.
vbKeyCapital 0x14 CAPS LOCK key.
vbKeyEscape 0x1B ESC key.
vbKeySpace 0x20 SPACEBAR key.
vbKeyPageUp 0x21 PAGE UP key.
vbKeyPageDown 0x22 PAGE DOWN key.
Programim object-oriented Faqa 455
vbKeyEnd 0x23 END key.
vbKeyHome 0x24 HOME key.
vbKeyLeft 0x25 LEFT ARROW key.
vbKeyUp 0x26 UP ARROW key.
vbKeyRight 0x27 RIGHT ARROW key.
vbKeyDown 0x28 DOWN ARROW key.
vbKeySelect 0x29 SELECT key.
vbKeyPrint 0x2A PRINT SCREEN key.
vbKeyExecute 0x2B EXECUTE key.
vbKeySnapshot 0x2C SNAPSHOT key.
vbKeyInsert 0x2D INS key.
vbKeyDelete 0x2E DEL key.
vbKeyHelp 0x2F HELP key.
vbKeyNumlock 0x90 NUM LOCK key.
KeyA Through KeyZ Are the Same as Their ASCII Equivalents: 'A' Through 'Z'
Constant Value Description
vbKeyA 65 A key.
vbKeyB 66 B key.
vbKeyC 67 C key.
vbKeyD 68 D key.
vbKeyE 69 E key.
vbKeyF 70 F key.
vbKeyG 71 G key.
Programim object-oriented Faqa 456
vbKeyH 72 H key.
vbKeyI 73 I key.
vbKeyJ 74 J key.
vbKeyK 75 K key.
vbKeyL 76 L key.
vbKeyM 77 M key.
vbKeyN 78 N key.
vbKeyO 79 O key.
vbKeyP 80 P key.
vbKeyQ 81 Q key.
vbKeyR 82 R key.
vbKeyS 83 S key.
vbKeyT 84 T key.
KeyA Through KeyZ (continued)
Constant Value Description
vbKeyU 85 U key.
vbKeyV 86 V key.
vbKeyW 87 W key.
vbKeyX 88 X key.
vbKeyY 89 Y key.
vbKeyZ 90 Z key.
Key0 Through Key9 Are the Same as Their ASCII Equivalents: '0' Through '9'
Programim object-oriented Faqa 457
Constant Value Description
vbKey0 48 0 key.
vbKey1 49 1 key.
vbKey2 50 2 key.
vbKey3 51 3 key.
vbKey4 52 4 key.
vbKey5 53 5 key.
vbKey6 54 6 key.
vbKey7 55 7 key.
vbKey8 56 8 key.
vbKey9 57 9 key.
Keys on the Numeric Keypad
Constant Value Description
vbKeyNumpad0 0x60 0 key.
vbKeyNumpad1 0x61 1 key.
vbKeyNumpad2 0x62 2 key.
vbKeyNumpad3 0x63 3 key.
vbKeyNumpad4 0x64 4 key.
vbKeyNumpad5 0x65 5 key.
vbKeyNumpad6 0x66 6 key.
vbKeyNumpad7 0x67 7 key.
vbKeyNumpad8 0x68 8 key.
vbKeyNumpad9 0x69 9 key.
vbKeyMultiply 0x6A MULTIPLICATION SIGN (*)
Programim object-oriented Faqa 458
vbKeyAdd 0x6B PLUS SIGN (+)
vbKeySeparator 0x6C ENTER key.
vbKeySubtract 0x6D MINUS SIGN (-)
vbKeyDecimal 0x6E DECIMAL POINT (.)
vbKeyDivide 0x6F DIVISION SIGN (/)
Function Keys
Constant Value Description
vbKeyF1 0x70 F1 key.
vbKeyF2 0x71 F2 key.
vbKeyF3 0x72 F3 key.
vbKeyF4 0x73 F4 key.
vbKeyF5 0x74 F5 key.
vbKeyF6 0x75 F6 key.
vbKeyF7 0x76 F7 key.
vbKeyF8 0x77 F8 key.
vbKeyF9 0x78 F9 key.
vbKeyF10 0x79 F10 key.
vbKeyF11 0x7A F11 key.
vbKeyF12 0x7B F12 key.
vbKeyF13 0x7C F13 key.
vbKeyF14 0x7D F14 key.
vbKeyF15 0x7E F15 key.
vbKeyF16 0x7F F16 key.
Programim object-oriented Faqa 459
Menu Accelerator Constants
Constant Value Description
vbMenuAccelCtrlA 1 User-defined shortcut keystrokes.
vbMenuAccelCtrlB 2 User-defined shortcut keystrokes.
vbMenuAccelCtrlC 3 User-defined shortcut keystrokes.
vbMenuAccelCtrlD 4 User-defined shortcut keystrokes.
vbMenuAccelCtrlE 5 User-defined shortcut keystrokes.
vbMenuAccelCtrlF 6 User-defined shortcut keystrokes.
vbMenuAccelCtrlG 7 User-defined shortcut keystrokes.
vbMenuAccelCtrlH 8 User-defined shortcut keystrokes.
vbMenuAccelCtrlI 9 User-defined shortcut keystrokes.
vbMenuAccelCtrlJ 10 User-defined shortcut keystrokes.
vbMenuAccelCtrlK 11 User-defined shortcut keystrokes.
Menu Accelerator Constants (continued)
Programim object-oriented Faqa 460
Constant Value Description
vbMenuAccelCtrlL 12 User-defined shortcut keystrokes.
vbMenuAccelCtrlM 13 User-defined shortcut keystrokes.
vbMenuAccelCtrlN 14 User-defined shortcut keystrokes.
vbMenuAccelCtrlO 15 User-defined shortcut keystrokes.
vbMenuAccelCtrlP 16 User-defined shortcut keystrokes.
vbMenuAccelCtrlQ 17 User-defined shortcut keystrokes.
vbMenuAccelCtrlR 18 User-defined shortcut keystrokes.
vbMenuAccelCtrlS 19 User-defined shortcut keystrokes.
vbMenuAccelCtrlT 20 User-defined shortcut keystrokes.
vbMenuAccelCtrlU 21 User-defined shortcut keystrokes.
vbMenuAccelCtrlV 22 User-defined shortcut keystrokes.
vbMenuAccelCtrlW 23 User-defined shortcut keystrokes.
vbMenuAccelCtrlX 24 User-defined shortcut keystrokes.
vbMenuAccelCtrlY 25 User-defined shortcut keystrokes.
vbMenuAccelCtrlZ 26 User-defined shortcut keystrokes.
Programim object-oriented Faqa 461
vbMenuAccelF1 27 User-defined shortcut keystrokes.
vbMenuAccelF2 28 User-defined shortcut keystrokes.
vbMenuAccelF3 29 User-defined shortcut keystrokes.
vbMenuAccelF4 30 User-defined shortcut keystrokes.
vbMenuAccelF5 31 User-defined shortcut keystrokes.
vbMenuAccelF6 32 User-defined shortcut keystrokes.
vbMenuAccelF7 33 User-defined shortcut keystrokes.
Menu Accelerator Constants (continued)
Constant Value Description
vbMenuAccelF8 34 User-defined shortcut keystrokes.
vbMenuAccelF9 35 User-defined shortcut keystrokes.
vbMenuAccelF11 36 User-defined shortcut keystrokes.
vbMenuAccelF12 37 User-defined shortcut keystrokes.
vbMenuAccelCtrlF1 38 User-defined shortcut keystrokes.
vbMenuAccelCtrlF2 39 User-defined shortcut keystrokes.
Programim object-oriented Faqa 462
vbMenuAccelCtrlF3 40 User-defined shortcut keystrokes.
vbMenuAccelCtrlF4 41 User-defined shortcut keystrokes.
vbMenuAccelCtrlF5 42 User-defined shortcut keystrokes.
vbMenuAccelCtrlF6 43 User-defined shortcut keystrokes.
vbMenuAccelCtrlF7 44 User-defined shortcut keystrokes.
vbMenuAccelCtrlF8 45 User-defined shortcut keystrokes.
vbMenuAccelCtrlF9 46 User-defined shortcut keystrokes.
vbMenuAccelCtrlF11 47 User-defined shortcut keystrokes.
vbMenuAccelCtrlF12 48 User-defined shortcut keystrokes.
vbMenuAccelShiftF1 49 User-defined shortcut keystrokes.
vbMenuAccelShiftF2 50 User-defined shortcut keystrokes.
vbMenuAccelShiftF3 51 User-defined shortcut keystrokes.
vbMenuAccelShiftF4 52 User-defined shortcut keystrokes.
vbMenuAccelShiftF5 53 User-defined shortcut keystrokes.
vbMenuAccelShiftF6 54 User-defined shortcut keystrokes.
Programim object-oriented Faqa 463
vbMenuAccelShiftF7 55 User-defined shortcut keystrokes.
Menu Accelerator Constants (continued)
Constant Value Description
vbMenuAccelShiftF8 56 User-defined shortcut keystrokes.
vbMenuAccelShiftF9 57 User-defined shortcut keystrokes.
vbMenuAccelShiftF11 58 User-defined shortcut keystrokes.
vbMenuAccelShiftF12 59 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF1 60 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF2 61 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF3 62 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF4 63 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF5 64 ser-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF6 65 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF7 66 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF8 67 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF9 68 ser-defined shortcut keystrokes.
Programim object-oriented Faqa 464
vbMenuAccelShiftCtrlF11 69 User-defined shortcut keystrokes.
vbMenuAccelShiftCtrlF12 70 User-defined shortcut keystrokes.
vbMenuAccelCtrlIns 71 User-defined shortcut keystrokes.
vbMenuAccelShiftIns 72 User-defined shortcut keystrokes.
vbMenuAccelDel 73 User-defined shortcut keystrokes.
vbMenuAccelShiftDel 74 User-defined shortcut keystrokes.
vbMenuAccelAltBksp 75 User-defined shortcut keystrokes.
Menu Control Constants
PopupMenu Method Alignment
Constant Value Description
vbPopupMenuLeftAlign 0 Pop-up menu left-aligned.
vbPopupMenuCenterAlign 4 Pop-up menu centered.
vbPopupMenuRightAlign 8 Pop-up menu right-aligned.
PopupMenu Mouse Button Recognition
Constant Value Description
vbPopupMenuLeftButton 0 Pop-up menu recognizes left mouse button only.
Programim object-oriented Faqa 465
vbPopupMenuRightButton 2 Pop-up menu recognizes right and left mouse buttons.
Miscellaneous Constants
ZOrder Method
Constant Value Description
vbBringToFront 0 Bring to front.
vbSendToBack 1 Send to back.
QueryUnload Method
Constant Value Description
vbAppWindows 2 Current Windows session ending.
vbFormMDIForm 4 MDI child form is closing because the MDI form is closing.
vbFormCode 1 Unload method invoked from code.
vbFormControlMenu 0 User has chosen Close command from the Control-menu box on a form.
vbAppTaskManager 3 Windows Task Manager is closing the application.
Shift Parameter Masks
Constant Value Description
Programim object-oriented Faqa 466
vbShiftMask 1 SHIFT key bit mask.
vbCtrlMask 2 CTRL key bit mask.
vbAltMask 4 ALT key bit mask.
Button Parameter Masks
Constant Value Description
vbLeftButton 1 Left mouse button.
vbRightButton 2 Right mouse button.
vbMiddleButton 4 Middle mouse button.
Application Start Mode
Constant Value Description
vbSModeStandalone 0 Stand-alone application.
vbSModeAutomation 1 OLE automation server.
LoadResPicture Method
Constant Value Description
vbResBitmap 0 Bitmap resource.
vbResIcon 1 Icon resource.
vbResCursor 2 Cursor resource.
Check Value
Constant Value Description
vbUnchecked 0 Unchecked.
Programim object-oriented Faqa 467
vbChecked 1 Checked.
vbGrayed 2 Grayed.
Mouse Pointer Constants
Constant Value Description
vbDefault 0 Default.
vbArrow 1 Arrow.
vbCrosshair 2 Cross.
vbIbeam 3 I beam.
vbIconPointer 4 Icon.
vbSizePointer 5 Size.
vbSizeNESW 6 Size NE, SW.
vbSizeNS 7 Size N, S.
vbSizeNWSE 8 Size NW, SE.
vbSizeWE 9 Size W, E.
vbUpArrow 10 Up arrow.
vbHourglass 11 Hourglass.
vbNoDrop 12 No drop.
vbArrowHourglass 13 Arrow and hourglass. (Only available in 32-bit Visual Basic 4.0.)
vbArrowQuestion 14 Arrow and question mark. (Only available in 32-bit Visual Basic 4.0.)
Programim object-oriented Faqa 468
vbSizeAll 15 Size all. (Only available in 32-bit Visual Basic 4.0.)
vbCustom 99 Custom icon specified by the MouseIcon property.
MsgBox Constants
MsgBox Arguments
Constant Value Description
vbOKOnly 0 OK button only (default)
vbOKCancel 1 OK and Cancel buttons.
vbAbortRetryIgnore 2 Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 Yes, No, and Cancel buttons.
vbYesNo 4 Yes and No buttons.
vbRetryCancel 5 Retry and Cancel buttons.
vbCritical 16 Critical message.
vbQuestion 32 Warning query.
vbExclamation 48 Warning message.
vbInformation 64 Information message.
vbDefaultButton1 0 First button is default (default)
vbDefaultButton2 256 Second button is default.
vbDefaultButton3 512 Third button is default.
vbApplicationModal 0 Application modal message box (default)
Programim object-oriented Faqa 469
vbSystemModal 4096 System modal message box.
MsgBox Return Values
Constant Value Description
vbOK 1 OK button pressed.
vbCancel 2 Cancel button pressed.
vbAbort 3 Abort button pressed.
vbRetry 4 Retry button pressed.
vbIgnore 5 Ignore button pressed.
vbYes 6 Yes button pressed.
vbNo 7 No button pressed.
OLE Container Control Constants
OLEType Property
Constant Value Description
vbOLELinked 0 OLE container control contains a linked object.
vbOLEEmbedded 1 OLE container control contains an embedded object.
vbOLENone 3 OLE container control doesn't contain an object.
OLETypeAllowed Property
Programim object-oriented Faqa 470
Constant Value Description
vbOLEEither 2 OLE container control can contain either a linked or an embedded object.
UpdateOptions Property
Constant Value Description
vbOLEAutomatic 0 Object is updated each time the linked data changes.
vbOLEFrozen 1 Object is updated whenever the user saves the linked document from within the application in which it was created.
vbOLEManual 2 Object is updated only when the Action property is set to 6 (Update)
AutoActivate Property
Constant Value Description
vbOLEActivateManual 0 OLE object isn't automatically activated.
vbOLEActivateGetFocus 1 Object is activated when the OLE container control gets the focus.
vbOLEActivateDoubleclick 2 Object is activated when the OLE container control is double-clicked.
vbOLEActivateAuto 3 Object is activated based on the object's default method of activation.
Programim object-oriented Faqa 471
SizeMode Property
Constant Value Description
vbOLESizeClip 0 Object's image is clipped by the OLE container control's borders.
vbOLESizeStretch 1 Object's image is sized to fill the OLE container control.
vbOLESizeAutoSize 2 OLE container control is automatically resized to display the entire object.
vbOLESizeZoom 3 Object's image is stretched but in proportion.
DisplayType Property
Constant Value Description
vbOLEDisplayContent 0 Object's data is displayed in the OLE container control.
vbOLEDisplayIcon 1 Object's icon is displayed in the OLE container control.
Updated Event Constants
Constant Value Description
vbOLEChanged 0 Object's data has changed.
vbOLESaved 1 Object's data has been saved by the application that created the object.
vbOLEClosed 2 Application file containing the linked object's data has been closed.
vbOLERenamed 3 Application file containing the linked object's data has been renamed.
Programim object-oriented Faqa 472
Special Verb Values
Constant Value Description
vbOLEPrimary 0 Default action for the object.
vbOLEShow -1 Activates the object for editing.
vbOLEOpen -2 Opens the object in a separate application window.
vbOLEHide -3 For embedded objects, hides the application that created the object.
vbOLEInPlaceUIActivate -4 All UI's associated with the object are visible and ready for use.
vbOLEInPlaceActivate -5 Object is ready for the user to click inside it and start working with it.
vbOLEDiscardUndoState -6 For discarding all record of changes that the object's application can undo.
Verb Flag Bit Masks
Constant Value Description
vbOLEFlagEnabled 0x0 Enabled menu item.
vbOLEFlagGrayed 0x1 Grayed menu item.
vbOLEFlagDisabled 0x2 Disabled menu item.
vbOLEFlagChecked 0x8 Checked menu item.
vbOLEFlagSeparator 0x800 Separator bar in menu item list.
Programim object-oriented Faqa 473
vbOLEMiscFlagMemStorage 0x1 Causes control to use memory to store the object while it's loaded.
vbOLEMiscFlagDisableInPlace 0x2 Forces OLE container control to activate objects in a separate window.
VBTranslateColor/OLETranslateColor Constants
Constant Value Description
vbInactiveCaptionText 0x80000013 Color of text in an inactive caption.
vb3DHighlight 0x80000014 Highlight color for 3-D display elements.
vb3DFace 0x8000000F Dark shadow color for 3-D display elements.
vbMsgBox 0x80000017 Background color for message boxes and system dialog boxes.
vbMsgBoxText 0x80000018 Color of text displayed in message boxes and system dialog boxes.
vb3DShadow 0x80000010 Color of automatic window shadows.
vb3DDKShadow 0x80000015 Darkest shadow.
vb3DLight 0x80000016 Second lightest of the 3-D colors (after vb3DHighlight)
Picture Object Constants
Programim object-oriented Faqa 474
Constant Value Description
vbPicTypeBitmap 1 Bitmap type of Picture object.
vbPicTypeMetafile 2 Metafile type of Picture object.
vbPicTypeIcon 3 Icon type of Picture object.
Programim object-oriented Faqa 475
Printer Object Constants
Printer Color Mode
Constant Value Description
vbPRCMMonochrome 1 Monochrome output.
vbPRCMColor 2 Color output.
Duplex Printing
Constant Value Description
vbPRDPSimplex 1 Single-sided printing.
vbPRDPHorizontal 2 Double-sided horizontal printing.
vbPRDPVertical 3 Double-sided vertical printing.
Printer Orientation
Constant Value Description
vbPRORPortrait 1 Documents print with the top at the narrow side of the paper.
vbPRORLandscape 2 Documents print with the top at the wide side of the paper.
Print Quality
Constant Value Description
vbPRPQDraft -1 Draft print quality.
vbPRPQLow -2 Low print quality.
vbPRPQMedium -3 Medium print quality.
vbPRPQHigh -4 High print quality.
Programim object-oriented Faqa 476
PaperBin Property
Constant Value Description
vbPRBNUpper 1 Use paper from the upper bin.
vbPRBNLower 2 Use paper from the lower bin.
vbPRBNMiddle 3 Use paper from the middle bin.
vbPRBNManual 4 Wait for manual insertion of each sheet of paper.
vbPRBNEnvelope 5 Use envelopes from the envelope feeder.
vbPRBNEnvManual 6 Use envelopes from the envelope feeder, but wait for manual insertion.
vbPRBNAuto 7 (Default)
vbPRBNTractor 8 Use paper fed from the tractor feeder.
Programim object-oriented Faqa 477
PaperBin Property (continued)
Constant Value Description
vbPRBNSmallFmt 9 Use paper from the small paper feeder.
vbPRBNLargeFmt 10 Use paper from the large paper bin.
vbPRBNLargeCapacity 11 Use paper from the large capacity feeder.
vbPRBNCassette 14 Use paper from the attached cassette cartridge.
PaperSize Property
Constant Value Description
vbPRPSLetter 1 Letter, 8 1/2 x 11 in.
vbPRPSLetterSmall 2 +A611Letter Small, 8 1/2 x 11 in.
vbPRPSTabloid 3 Tabloid, 11 x 17 in.
vbPRPSLedger 4 Ledger, 17 x 11 in.
vbPRPSLegal 5 Legal, 8 1/2 x 14 in.
vbPRPSStatement 6 Statement, 5 1/2 x 8 1/2 in.
vbPRPSExecutive 7 Executive, 7 1/2 x 10 1/2 in.
vbPRPSA3 8 A3, 297 x 420 mm.
vbPRPSA4 9 A4, 210 x 297 mm.
vbPRPSA4Small 10 A4 Small, 210 x 297 mm.
vbPRPSA5 11 A5, 148 x 210 mm.
vbPRPSB4 12 B4, 250 x 354 mm.
vbPRPSB5 13 B5, 182 x 257 mm.
vbPRPSFolio 14 Folio, 8 1/2 x 13 in.
Programim object-oriented Faqa 478
vbPRPSQuarto 15 Quarto, 215 x 275 mm.
vbPRPS10x14 16 10 x 14 in.
vbPRPS11x17 17 11 x 17 in.
vbPRPSNote 18 Note, 8 1/2 x 11 in.
vbPRPSEnv9 19 Envelope #9, 3 7/8 x 8 7/8 in.
vbPRPSEnv10 20 Envelope #10, 4 1/8 x 9 1/2 in.
vbPRPSEnv11 21 Envelope #11, 4 1/2 x 10 3/8 in.
vbPRPSEnv12 22 Envelope #12, 4 1/2 x 11 in.
vbPRPSEnv14 23 Envelope #14, 5 x 11 1/2 in.
vbPRPSCSheet 24 C size sheet.
vbPRPSDSheet 25 D size sheet.
vbPRPSESheet 26 E size sheet.
vbPRPSEnvDL 27 Envelope DL, 110 x 220 mm.
vbPRPSEnvC3 29 Envelope C3, 324 x 458 mm.
vbPRPSEnvC4 30 Envelope C4, 229 x 324 mm.
vbPRPSEnvC5 28 Envelope C5, 162 x 229 mm.
vbPRPSEnvC6 31 Envelope C6, 114 x 162 mm.
vbPRPSEnvC65 32 Envelope C65, 114 x 229 mm.
PaperSize Property (continued)
Constant Value Description
vbPRPSEnvB4 33 Envelope B4, 250 x 353 mm.
vbPRPSEnvB5 34 Envelope B5, 176 x 250 mm.
vbPRPSEnvB6 35 Envelope B6, 176 x 125 mm.
vbPRPSEnvItaly 36 Envelope, 110 x 230 mm.
Programim object-oriented Faqa 479
vbPRPSEnvMonarch 37 Envelope Monarch, 3 7/8 x 7 1/2 in.
vbPRPSEnvPersonal 38 Envelope, 3 5/8 x 6 1/2 in.
vbPRPSFanfoldUS 39 U.S. Standard Fanfold, 14 7/8 x 11 in.
vbPRPSFanfoldStdGerman 40 German Standard Fanfold, 8 1/2 x 12 in.
vbPRPSFanfoldLglGerman 41 German Legal Fanfold, 8 1/2 x 13 in.
vbPRPSUser 256 User-defined.
RasterOp Constants
Constant Value Description
vbDstInvert 0x00550009 Inverts the destination bitmap.
vbMergeCopy 0x00C000CA Combines the pattern and the source bitmap.
vbMergePaint 0x00BB0226 Combines the inverted source bitmap with the destination bitmap by using Or.
vbNotSrcCopy 0x00330008 Copies the inverted source bitmap to the destination.
vbNotSrcErase 0x001100A6 Inverts the result of combining the destination and source bitmaps by using Or.
vbPatCopy 0x00F00021L Copies the pattern to the destination bitmap.
Programim object-oriented Faqa 480
vbPatInvert 0x005A0049L Combines the destination bitmap with the pattern by using Xor.
vbPatPaint 0x00FB0A09L Combines the inverted source bitmap with the pattern by using Or. Combines the result of this operation with the destination bitmap by using Or.
vbSrcAnd 0x008800C6 Combines pixels of the destination and source bitmaps by using And.
RasterOp Constants (continued)
Constant Value Description
vbSrcCopy 0x00CC0020 Copies the source bitmap to the destination bitmap.
vbSrcErase 0x00440328 Inverts the destination bitmap and combines the result with the source bitmap by using And.
vbSrcInvert 0x00660046 Combines pixels of the destination and source bitmaps by using Xor.
vbSrcPaint 0x00EE0086 Combines pixels of the destination and source bitmaps by using Or.
Shell Constants
Constant Value Description
Programim object-oriented Faqa 481
vbHide 0 Window is hidden and focus is passed to the hidden window.
vbNormalFocus 1 Window has focus and is restored to its original size and position.
vbMinimizedFocus 2 Window is displayed as an icon with focus.
vbMaximizedFocus 3 Window is maximized with focus.
vbNormalNoFocus 4 Window is restored to its most recent size and position. The currently active window remains active.
vbMinimizedNoFocus 6 Window is displayed as an icon. The currently active window remains active.
StrConv Constants
Constant Value Description
vbUpperCase 1 Uppercases the string.
vbLowerCase 2 Lowercases the string.
vbProperCase 3 Uppercases first letter of every word in string.
vbWide* 4 Converts narrow (single-byte)(double-byte)
vbNarrow* 8 Converts wide (double-byte)(single-byte)
vbKatakana** 16 Converts Hiragana characters in string to Katakana characters.
Programim object-oriented Faqa 482
vbHiragana** 32 Converts Katakana characters in string to Hiragana characters.
vbUnicode*** 64 Converts the string to Unicode using the default code page of the system.
vbFromUnicode*** 128 Converts the string from Unicode to the default code page of the system.
______________________________________________________
Variant Type Constants
Constant Value Description
vbVEmpty 0 Empty (uninitialized)
vbVNull 1 Null (no valid data)
vbVInteger 2 Integer data type.
vbVLong 3 Long integer data type.
vbVSingle 4 Single-precision floating-point data type.
vbVDouble 5 Double-precision floating-point data type.
vbVCurrency 6 Currency (scaled integer)
vbVDate 7 Date data type.
vbVString 8 String data type.
Programim object-oriented Faqa 483
VarType Constants
Constant Value Description
vbEmpty 0 Uninitialized (default)
vbNull 1 Contains no valid data.
vbInteger 2 Integer.
vbLong 3 Long integer.
vbSingle 4 Single-precision floating-point number.
vbDouble 5 Double-precision floating-point number.
vbCurrency 6 Currency.
vbDate 7 Date.
vbString 8 String.
vbObject 9 OLE Automation object.
vbError 10 Error.
vbBoolean 11 Boolean.
vbVariant 12 Variant (used only for arrays of Variants)
vbDataObject 13 Non-OLE Automation object.
vbByte 17 Byte
vbArray 8192 Array.
Programim object-oriented Faqa 484
11. Appendix II. Common Dialog Box Constants
CommonDialog Control Constants
File Open/Save Dialog Box Flags
Constant Value Description
cdlOFNReadOnly 0x1 Checks Read-Only check box for Open and Save As dialog boxes.
cdlOFNOverwritePrompt 0x2 Causes the Save As dialog box to generate a message box if the selected file already exists.
cdlOFNHideReadOnly 0x4 Hides the Read-Only check box.
cdlOFNNoChangeDir 0x8 Sets the current directory to what it was when the dialog box was invoked.
cdlOFNHelpButton 0x10 Causes the dialog box to display the Help button.
cdlOFNNoValidate 0x100 Allows invalid characters in the returned filename.
cdlOFNAllowMultiselect 0x200 Allows the File Name list box to have multiple selections.
cdlOFNExtensionDifferent 0x400 The extension of the returned filename is different from the extension set by the DefaultExt property.
Programim object-oriented Faqa 485
cdlOFNPathMustExist 0x800 User can enter only valid path names.
cdlOFNFileMustExist 0x1000 User can enter only names of existing files.
cdlOFNCreatePrompt 0x2000 Sets the dialog box to ask if the user wants to create a file that doesn't currently exist.
File Open/Save Dialog Box Flags (continued)
Constant Value Description
cdlOFNShareAware 0x4000 Sharing violation errors will be ignored.
cdlOFNNoReadOnlyReturn 0x8000 The returned file doesn't have the Read-Only attribute set and won't be in a write-protected directory.
cdlOFNExplorer 0x0008000 Use the Explorer-like Open A File dialog box template. (Windows 95 only.)
cdlOFNNoDereferenceLinks 0x00100000 Do not dereference shortcuts (shell links) default, choosing a shortcut causes it to be dereferenced by the shell. (Windows 95 only.)
cdlOFNLongNames 0x00200000 Use Long filenames. (Windows 95 only.)
Color Dialog Box Flags
Constant Value Description
cdlCCRGBInit 0x1 Sets initial color value for the dialog box.
Programim object-oriented Faqa 486
cdlCCFullOpen 0x2 Entire dialog box is displayed, including the Define Custom Colors section.
cdlCCPreventFullOpen 0x4 Disables the Define Custom Colors section of the dialog box.
cdlCCHelpButton 0x8 Dialog box displays a Help button.
Fonts Dialog Box Flags
Constant Value Description
cdlCFScreenFonts 0x1 Dialog box lists only screen fonts supported by the system.
cdlCFPrinterFonts 0x2 Dialog box lists only fonts supported by the printer.
cdlCFBoth 0x3 Dialog box lists available screen and printer fonts.
cdlCFHelpButton 0x4 Dialog box displays a Help button.
cdlCFEffects 0x100 Dialog box enables strikeout, underline, and color effects.
cdlCFApply 0x200 Dialog box enables the Apply button.
cdlCFANSIOnly 0x400 Dialog box allows only a selection of fonts that use the Windows character set.
cdlCFNoVectorFonts 0x800 Dialog box should not allow vector-font selections.
Fonts Dialog Box Flags (continued)
Constant Value Description
cdlCFNoSimulations 0x1000 Dialog box should not allow graphic device interface (GDI)
Programim object-oriented Faqa 487
cdlCFLimitSize 0x2000 Dialog box should select only font sizes within the range specified by the Min and Max properties.
cdlCFFixedPitchOnly 0x4000 Dialog box should select only fixed-pitch fonts.
cdlCFWYSIWYG 0x8000 Dialog box should allow only the selection of fonts available to both the screen and printer.
cdlCFForceFontExist 0x10000 An error dialog box is displayed if a user selects a font or style that doesn't exist.
cdlCFScalableOnly 0x20000 Dialog box should allow only the selection of scalable fonts.
cdlCFTTOnly 0x40000 Dialog box should allow only the selection of TrueType fonts.
cdlCFNoFaceSel 0x80000 No font name selected.
cdlCFNoStyleSel 0x100000 No font style selected.
cdlCFNoSizeSel 0x200000 No font size selected.
Printer Dialog Box Flags
Constant Value Description
cdlPDAllPages 0x0 Returns or sets state of All Pages option button.
cdlPDCollate 0x10 Returns or sets state of Collate check box.
cdlPDDisablePrintToFile 0x80000 Disables the Print To File check box.
cdlPDHidePrintToFile 0x100000 The Print To File check box isn't displayed.
Programim object-oriented Faqa 488
cdlPDNoPageNums 0x8 Returns or sets the state of the Pages option button.
cdlPDNoSelection 0x4 Disables the Selection option button.
cdlPDNoWarning 0x80 Prevents a warning message when there is no default printer.
cdlPDPageNums 0x2 Returns or sets the state of the Pages option button.
cdlPDPrintSetup 0x40 Displays the Print Setup dialog box rather than the Print dialog box.
Printer Dialog Box Flags (continued)
Constant Value Description
cdlPDPrintToFile 0x20 Returns or sets the state of the Print To File check box.
cdlPDReturnDC 0x100 Returns a device context for the printer selection value returned in the hDC property of the dialog box.
cdlPDReturnDefault 0x400 Returns default printer name.
cdlPDReturnIC 0x200 Returns an information context for the printer selection value returned in the hDC property of the dialog box.
cdlPDSelection 0x1 Returns or sets the state of the Selection option button.
cdlPDHelpButton 0x800 Dialog box displays the Help button.
cdlPDUseDevModeCopies 0x40000 Sets support for multiple copies action; depends upon whether or not printer supports multiple copies.
Programim object-oriented Faqa 489
CommonDialog Error Constants
Constant Value Description
cdlAlloc &H7FF0& Couldn't allocate memory for FileName or Filter property.
cdlCancel &H7FF3& Cancel was selected.
cdlDialogFailure &H8000& The function failed to load the dialog box.
cdlFindResFailure &H7FF9& The function failed to load a specified resource.
cdlHelp &H7FEF& Call to Windows Help failed.
cdlInitialization &H7FFD& The function failed during initialization.
cdlLoadResFailure &H7FF8& The function failed to load a specified string.
cdlLockResFailure &H7FF7& The function failed to lock a specified resource.
cdlMemAllocFailure &H7FF6& The function was unable to allocate memory for internal data structures.
cdlMemLockFailure &H7FF5& The function was unable to lock the memory associated with a handle.
cdlNoFonts &H5FFE& No fonts exist.
cdlBufferTooSmall &H4FFC& The buffer at which the member lpstrFile points is too small.
cdlInvalidFileName &H4FFD& Filename is invalid.
cdlSubclassFailure &H4FFE& An attempt to subclass a list box failed due to insufficient memory.
Programim object-oriented Faqa 490
cdlCreateICFailure &H6FF5& The PrintDlg function failed when it attempted to create an information context.
cdlDndmMismatch &H6FF6& Data in the DevMode and DevNames data structures describe two different printers.
cdlGetDevModeFail &H6FFA& The printer device driver failed to initialize a DevMode data structure.
cdlInitFailure &H6FF9& The PrintDlg function failed during initialization.
cdlLoadDrvFailure &H6FFB& The PrintDlg function failed to load the specified printer's device driver.
CommonDialog Error Constants (continued)
Constant Value Description
cdlNoDefaultPrn &H6FF7& A default printer doesn't exist.
cdlNoDevices &H6FF8& No printer device drivers were found.
cdlParseFailure &H6FFD& The CommonDialog function failed to parse the strings in the [devices] section of WIN.INI.
cdlPrinterCodes &H6FFF& The PDReturnDefault flag was set, but either the hDevMode or hDevNames field was nonzero.
cdlPrinterNotFound &H6FF4& The [devices] section of WIN.INI doesn't contain an entry for the requested printer.
cdlRetDefFailure &H6FFC& The PDReturnDefault flag was set, but either the hDevMode or hDevNames field was nonzero.
cdlSetupFailure &H6FFE& Failed to load required resources.
Programim object-oriented Faqa 491
Programim object-oriented Faqa 492
12. Kodet ASCII
Kodet 0-127
Code Char Code Char Code Char Code Char
0 <NUL> 32 <space> 64 @ 96 `
1 <SOH> 33 ! 65 A 97 a
2 <STX> 34 " 66 B 98 b
3 <ETX> 35 # 67 C 99 c
4 <EOT> 36 $ 68 D 100 d
5 <ENQ> 37 % 69 E 101 e
6 <ACK> 38 & 70 F 102 f
7 <BEL> 39 ' 71 G 103 g
8 <BS> 40 ( 72 H 104 h
9 <HT> 41 ) 73 I 105 i
10 <LF> 42 * 74 J 106 j
11 <VT> 43 + 75 K 107 k
12 <FF> 44 , 76 L 108 l
13 <CR> 45 - 77 M 109 m
14 <SO> 46 . 78 N 110 n
15 <SI> 47 / 79 O 111 o
16 <DLE> 48 0 80 P 112 p
17 <DC1> 49 1 81 Q 113 q
18 <DC2> 50 2 82 R 114 r
19 <DC3> 51 3 83 S 115 s
20 <DC4> 52 4 84 T 116 t
21 <NAK> 53 5 85 U 117 u
22 <SYN> 54 6 86 V 118 v
23 <ETB> 55 7 87 W 119 w
24 <CAN> 56 8 88 X 120 x
25 <EM> 57 9 89 Y 121 y
Programim object-oriented Faqa 493
26 <> 58 : 90 Z 122 z
27 <SUB> 59 ; 91 [ 123 {
28 <ESC> 60 < 92 \ 124 |
29 <GS> 61 = 93 ] 125 }
30 <RS> 62 > 94 ^ 126 ~
31 <US> 63 ? 95 _ 127 <DEL>
Kodet 128-255
Programim object-oriented Faqa 494