Sei sulla pagina 1di 5

1/29/2017 VisualBasicCh.

2Notes,page1

CIS230,VisualBasic

Ch.2Notes,page1

Objective#1:Usetextboxes,frames,checkboxes,optionbuttons,images,shapes,andlineseffectively.

AprogramshouldtakeadvantageofthevisualnatureofVBprograms.Itiseasytousetextboxes,frames,checkboxes,shapes,lines,etc.but
onemustbecarefultomakeuserfriendlinessapriority.LookcloselyatcommercialWindowsapplicationsthatyouuseonyourdesktopPCto
seehowprofessionaldevelopersusesuchcontrols.
Atextboxshouldbeusediftheuseristoenterormodifytext.Itusuallyhasawhitebackgroundandcancontainalargeamountoftextifits
MultiLinepropertyissettoTrue.Labelsontheotherhandshouldbeusediftheuserisnotmeanttoenterorchangetext.Forthisreason,itis
sometimesnotnecessarytorenamelabelswiththelblprefixifthecontentsandpropertiesofthelabelaretoremainunchangedthroughoutthe
program'sexecution.Textboxesshouldberenamedwithpurposefulnamesthatbeginwiththetxtprefix.
Astringliteralisasetofcharactersthatareenclosedindoublequotes.Forexample,"VisualBasic"isastringliteralthatiscontains12
characters(countingtheblankspace.)Sometimes,wecallstringliteralssimply"strings".
ToassignastringliteraltotheTextpropertyofatextboxduringruntime,youcanuseastatementlike,txtUserName.Text=
"JohnDoe"
Toassignthecontentsofonetextbox'sTextpropertytoanother's,youcanuseastatementlike,txtUserName.Text=
txtProgrammerName.Text.Inthiscase,whateverwascontainedintxtProgrammerNameisnowcontainedintxtUserName,also.
WhatpreviouslywasstoredwithintxtUserNamewasoverwrittenandlost.Thisisanexampleofanassignmentstatementwhich
evaluatesfromrighttoleft(asinmostcomputerlanguages.)
Bytheway,youmustfirstsetatextbox'sMultilinepropertytoTruetobeabletosetitsAlignmentproperty.
Framesaremeanttogrouprelatedobjectsonaformwindow.Aframeisindicatedbyarectangle.Youshouldfirstcreatetheframebysingle
clickingitsTooliconandthendrawingitontheformwindowwithyourmouse.Then,youshouldcreatetheobjectswithinitsboundariesto
ensurethatVBtreatsthemasbeinginsidetheframe.
Optionbuttons(sometimescalledradiobuttons)areroundcirclesthatcanbeselectedbytheuser.Onlyoneoptionbuttonthoughcanbe
chosenwithanysetofrelatedones.Thisaspectdistinguishesthemfromcheckboxes(seebelow)whicharesquares.Relatedoptionbuttons
shouldbeplacedwithinaframesothattheyworkcorrectly.Optionbuttonsrequiretheusertoselectonewithanygroupbutifyourformhas
morethanonesetofoptionbuttons,yourcodemayhavealogicalerrorifyouarenotcarefultouseaframearoundeachset.TheVBnaming
prefixforoptionbuttonsisopt.
Checkboxesareveryusefulforobtaininguserinput.Ausercanselectanynumberofcheckboxeswithinagroup.TheVBnamingprefixfor
checkboxesischk.
Imagescanenhanceaprogramvisually.VisualBasicsupportsanumberoftypesofgraphicsandimages.Usetheimagecontroltoplace
imagesonyourform.Besurethoughtosettheimage'sPicturepropertycorrectlysothatitisdisplayedproperly.Whiletherearedozensor
hundredsoftypesofcomputergraphicsandimages,VisualBasicallowsyoutouseimageswiththefollowingextensions:.bmp,.wmf,.ico,
.dib.,.gif,.jpg,.emf.,or.cur.Notethat.gifand.jpgarecommonontheWorldWideWeb,soyoucandownloadthosetypesofgraphicsfroma
WebpageandthenusethemwithinyourVBprogram(aslongasyoudon'tbreakcopyrightlaws.)Youshouldprobablylocatetheseimages
withinthefolderthatyoucreatedforyourVBproject.
Shapeandlinecontrolscanbeusedtomakeyourformwindowlookappealing.Thenamingprefixesfortheseobjectsare.shpand.lin,
respectively.

http://www.minich.com/education/racc/visualbasic/cis230ch2/ch2notes1.htm 1/5
1/29/2017 VisualBasicCh.2Notes,page1

Objective#2:SettheAppearancepropertytomakecontrolsappearflatorthreedimensional.

ExperimentwiththeAppearancepropertyinvarioustypesofcontrolstoachievedifferenteffects.

Objective#3:Selectmultiplecontrolsandmovethem,alignthem,andsetcommonproperties.

Ifyouhavemanycontrolsonaformwindowandwouldliketomovethemallatonce,simplychoosethePointertoolanddragtomakea
rectanglearoundthem.Thiswillselectallofthematonce.Thenyoucandragthewholesetbyclickingwithinanyoftheselectedobjects.You
caneffectthecommonpropertiesofthemultiplyselectedcontrolsbymakingchangestothePropertywindow.Thisallowsyoutobuild
consistencyintoyourVBprogramanditsavestime.
YoucanalsomultiplyselectnumerouscontrolsbyholdingdowntheShiftorControl(Ctrl)keywhileyouselecteachone.
ThereareanumberofalignmentoptionsundertheFormat/Alignmenuoptions.Youmustfirstmultiplyselectthecontrolsthatwishtoalign
though.
YoucanalsoaligncontrolsbysettingtheirLeft,Top,andWidthproperties.Themeasurementsthatyouusetherearetwips,whereonetwip
is1/1,440ofaninch.Whileyoucouldsetanobject'sWidthpropertyto1,440twips,itstillmaynotappeartobeexactlyoneinchonyour
screenduetodifferencesinmonitorresolution.
Atanytime,youcanrightclickonthebackgroundareaoftheformwindowandchooseLockControlsfromtheshortcutmenu.Thiswill
preservethearrangementofcontrolsthatyoutediouslyalignedorplaced.

Objective#4:Makeyourprojectseasyfortheusertounderstandandoperatebydefiningaccesskeys,settingadefaultandacancelbutton,
controllingthetabsequence,resettingthefocusduringprogramexecution,andcausingToolTipstoappear.

Youshouldalwaysassumethatyourprogramisgoingtobeusedby"knuckleheads",thatisnovicecomputerusers.Givingtheseusersmultiple
waystoaccomplishtasksinyourprogramwillprovideforamoreuserfriendlyexperience.Strivetomakedirectionsandpromptmessages
clear.
Setupaccesskeys(keyboardshortcuts)tomakeitpossibleforausertokeephishandsonthekeyboardandtoavoidhavingtoreachforthe
mouse.Somepeoplepreferusingthekeyboardinthiswayevenifyoudon't.Forexample,tosaveanactivedocumentinmanyWindows
applications,ausercantypeCtrl+S.Thiskeyboardshortcuthasbecomeastandardinallapplications.TouseaccesskeysinVB,youmust
precedeoneofthelettersinanobject'sCaptionproperty.Theletterthatyouchosewillbeunderlinedintheformwindow.Thiswillallowthe
usertoselectthatobjectbypressingAlt+[theletteryouchose].Neverusethesameaccesskeyfortwoobjectsthatwouldappearontheform
windowsimultaneously.Thiswillconfusetheuserandpossiblycrashyourprogram.Followaccesskeystandardsthatyouseeincommercial
Windowsapplications.
Youcansetonecommandbuttononaformwindowtobethedefaultbutton.SimplysetitsDefaultpropertytoTrue.Thiswillcausethat
buttontobeselectedwhentheuserpressestheEnterkey.Italsocausesthebuttontohaveadarkeroutlinethanothercommandbuttons.
MostDOSandWindowssoftwareusestheEsc(escape)keyintheupperleftcornerofthekeyboardtoallowtheuserto"backoutof"orcancel
thecurrentscreenorwindow.Icallthisthe"escapehatch".IfyouhaveaCancelcommandbuttononyourform,itisdefinitelyagoodideato
setitsCancelpropertytoTrue,causingittobeselectediftheusertypedtheEsckey.
Atanytime,oneofthecontrolsonaformhasthe"focus".Thiscontrolisoftennotedwithadottedlineorotherindicationthatithasthefocus.
IftheuserpressestheEnterkey,oftenitisthecontrolwiththefocusthatbecomesselected.WhentheuserpressestheTabkey,thefocus
changestoanothercontrol.BycarefullymanipulatingtheTabIndexpropertyofvariouscontrolsonyourform,youcanmakeyourprogram
muchmorelogicalanduserfriendly.Whentheprogrambegins,thecontrolwiththelowestTabIndex(usuallystartsat0)hasthefocus.
http://www.minich.com/education/racc/visualbasic/cis230ch2/ch2notes1.htm 2/5
1/29/2017 VisualBasicCh.2Notes,page1

Youcanresetthefocustoonecontrolbyusingastatementlike,txtUserName.SetFocus.Thiswouldcausethetextboxnamed
txtUserNametoreceivethefocusnomatterwhatit'sTabIndexpropertymightbe.
ToolTipsarethelittlepopupwindowsthatappearwhenyoumovethemouseoversomeobjectsinvarioussoftwareapplications.YourVB
programwillbemoreuserfriendlyifyousettheToolTipspropertyofvariouscontrolstotextwordsorphrasesthatindicatetheirpurpose.By
leavingtheToolTippropertyempty,theobjectwillnothaveaToolTip.

Objective#5:Clearthecontentsoftextboxesandlabels.

Programmersreferto""astheemptystring.Itissometimescalledthenullstring.Thatis,bytypingdoublequoteswithnospacesinbetween,
youareindicatinganemptystringliteral.ToclearthecontentsofatextboxnamedtxtUserName,youwouldsimplyusethestatement,
txtUserName.Text="".Toclearalabel'sCaptionproperty,youmightuse,lblName.Caption="".Ofcourse,thesestatements
wouldworkatruntimebutyoucouldalsoclearthesepropertiesinthePropertieswindowduringdesigntime.

Objective#6:Changefontattributes,suchasbold,italic,underline,size,andcolor,duringprogramexecution.

OneobjectinVBisunliketheothers.ItistheFontobject.AfontobjectcannotbecreatedfromtheToolbox.Rather,youmustchoosetheFont
propertywithintextboxes,labels,etc.tomanipulatethepropertiesoftheFontobject.
Youhavemuchcontrolovertheappearanceofanobject'sfontduringruntimeordesigntime.Astatementlike,txtPlace.Font.Bold=
True,wouldmakethetextwithinatextboxappearbold.Youcouldalsoachievethiseffectduringdesigntimesimplybytypingonthe
Propertiessettingsinthetextbox'sFontproperty.
ExperimentwiththeFontobjecttoseewhatkindsofappearancestextcanhaveinVB.
AnswertheFeedback2.2questionsonp.67atthistime.
VBhas8builtinconstantcolorsnamedvbBlack,vbRed,vbGreen,vbYellow,vbBlue,vbMagenta,vbCyan,andvbWhitethatmaybeused
withinassignmentstatements.YouwillseeapaletteofcolorchoiceswithinthePropertiessettingsofpropertiessuchasForeColor,FillColor,
BackColor,etc.ThesecolorchoicesaredenotedwithhexadecimalnumbersthatrepresentthestandardrangeofcomputerRGBcolors.

DoFeedback2.2#13onp.67atthistime.

Objective#7:CodemultiplestatementsforonecontrolusingtheWithandEndWithstatements.

Tosavetimeandbeanefficientprogrammer,youcanusetheWithstatementtomanipulatevariouspropertiesofanobjectatonce.Bytyping,

WithObjectName
.PropertyOne=????
.PropertyTwo=????
.PropertyThree=???
EndWith

youcanaffectpropertieswithouthavingtotypetheobject'snamesomanytimes.

NoticethatthestatementsbetweenWithandEndWithareindentedtoimprovethereadabilityofyourprogram.

http://www.minich.com/education/racc/visualbasic/cis230ch2/ch2notes1.htm 3/5
1/29/2017 VisualBasicCh.2Notes,page1

Eachclassofcontrolhasapropertythatisconsideredtobeitsdefaultproperty.Youdonothavetoactuallynamethedefaultpropertywithin
statements.Forexample,sincethedefaultpropertyofalabelisitsCaptionpropertyyoucouldusethisstatementtoassignitslabel
lblName="JohnDoe"insteadofthisstatementlblName.Caption="JohnDoe".Makeanefforttolearnthedefaultpropertiesof
thevariousVBcontrolssothatyoucanwritecodemoreefficiently.ItwillalsohelpyouunderstandcodewrittenbyprofessionalVB
programmers.

Chartofcontrolsandtheirdefaultproperties

Control DefaultProperty
Checkbox Value
Combobox Text
Commandbutton Value
Frame Caption
Horizontalscroll
Value
bar
Image Picture
Label Caption
Line Visible
Listbox Text
Menu Enabled
Optionbutton Value
Picturebox Picture
Shape Shape
Textbox Text
Timer Enabled
Verticalscrollbar Value

Objective#8:Concatenate(join)stringsoftext.

Whentwostringliterals(thatis,charactersenclosedindoublequotes)arejoinedtogetherwithoutplacinganyspacesbetweenthem,
programmerscallthisconcatenation.ToconcatenatetwostringsinVB,youshouldusetheampersand(&)symbol.
Example:Toconcatenatethetextwithintwoseparatetextboxesandplacetheconcatenatedtextintoalabel,youcouldusethisstatement,

lblUserName=txtFirstName&txtSecondName

http://www.minich.com/education/racc/visualbasic/cis230ch2/ch2notes1.htm 4/5
1/29/2017 VisualBasicCh.2Notes,page1

Sincetheampersandisusedtoconcatenatetext,itiscalledtheconcatenationoperator.WhileVBsometimesallowstheplus(+)symboltobe
usedforconcatenation,youshouldavoidthissinceitiseasytomistakeitforthemathematicsoperationofaddition.

Objective#9:MakeacontrolvisibleorinvisiblebysettingitsVisibleproperty.

Youcanmakeanobjectdisappearduringruntimewithastatementlike,txtHeading.Visible=False
YoucancertainlyhideanobjectduringdesigntimebysettingitsVisiblepropertytoFalseandthenmakeitappearduringprogramexecution
bysettingitsVisiblepropertytoTrueasabove.

DotheReviewQuestions#117onpp.79,80atthistime.

CIS230HomePage|Mr.Minich'sEducationHomePage|Minich.comWebDesign

http://www.minich.com/education/racc/visualbasic/cis230ch2/ch2notes1.htm 5/5

Potrebbero piacerti anche