Sei sulla pagina 1di 3

1/29/2017 VisualBasicCh.

5Notes,page1

CIS230,VisualBasic

Ch.5Notes

Objective#1:Createmenusandsubmenusforprogramcontrol.

MostmodernWindowsprogramsusecommonWindowsmenustogivetheuserdirectaccesstokeyfunctionsandcommands.VisualBasic
makesiteasytocreatesuchmenusinyourprogramsviatheMenuEditorfromtheToolsmenu.Whileitistruethatanythingdonefroma
menuoptioncouldalsobedonefromacommandbutton,itissometimesbettertogiveusersdropdownmenucommandsthantoclutteraform
withalotofcommandbuttons.
Menucommandsarecontrolslikecommandbuttons,textboxes,etc.EachmenucommandhasitsownNameandCaptionproperties.Menu
commandscanrespondtoClickeventsaswell.Theprefixforamenucontrolis"mnu".
ItiseasytousethespecialMenuEditorwindowtocreatemenus.
YoushouldfollowWindowsstandardsregardingtheavailabilityandplacementofparticularmenucommands.Forexample,yourfirstmenu
CaptionshouldbeFile,with'F'astheaccesskey.Therefore,theCaptionforthismenucommandwouldbe&File.
Furthermore,youshouldfollowtheconventionofincludingthetopentryonamenuwithintheNamepropertiesofothermenucommandson
thesamemenu.ForthePrintcommandwhichshouldbeplacedsomewhereontheFilemenuyoushouldusethenamemnuFilePrint.
WhenauserclicksoneofthemenucommandsliketheExitcommand(whichshouldbeontheFilemenubytheway)themnuFileExit_Click
eventwouldtrigger.
Asubmenuisindicatedbyatriangletotherightofamenucommand.Thetriangleindicatesthattheusercanselectfromseveralothermenu
commandsbymovinghis/hermouseoverthearrow.Oftenthesesubmenucommandsappeartotherightoftheoriginalpulldownmenu.
WithintheMenuEditoritispossibletosetcertainmenucommandsassubmenucommandsbyclickingontheRightarrowbuttonsothatdots
(....)appearandthesubmenucommandisindented.
Itisalsopossibletoaddseparatorbarswithinmenustoindicatecertaingroupingsofcommandsaccordingtotheirpurpose.Aseparatorbar
willbecreatedifyoutypeahyphen()intheCaptionofamenucommand.
Toaddcodetoamenucommand,yousimplyselectthemenucommandindesigntimetoseeitscodewindow.
TheChecked,Enabled,andVisiblepropertiesofmenucommandscanbeusedtoprovideastandardWindowslookandfeeltoyourmenu.
Theycanalsomakeyourprogrammoreuserfriendly.
Withinamenucommand'scode,youcancausethemenucommandtoappearwithacheckmarkwithastatementlike
mnuViewToolbar.Checked=True
YoucanalsousekeyboardshortcutswhichareinvokedbyhavingtheuserpressCtrl+[anotherkey]toinvokemenucommandswhichare
notontopofmenulist(asopposedtoAlt+[anotherkey]foraccesskeys).TheMenuEditorallowskeyboardshortcuts(likeCtrl+PforPrint)
tobesetupwithmenucommands.

Objective#2:DisplayandusetheWindowscommondialogboxes.

Thereareanumberofpredefined,standardWindowsdialogboxesthatcanbeusedinyourVBproject.Youfirsthavetoaddthecommon
dialogcontrol(prefix,dlg)toyourform.Thiscontrolwillbeinvisibleduringruntimebutyoumustplaceitontheformindesigntimeinorder
tomakeuseofcommondialogboxes.Youonlyneedonecommondialogcontrolonyourformtobeabletouseitnumeroustimes.
TohavethestandardColordialogboxappearonthescreen,youusethestatementdlgCommon.ShowColor(wheredlgCommonis
thenamethatyougavetothecommondialogcontrolonyourformandShowColorisamethodassociatedwiththecommondialogbox).Then
http://www.minich.com/education/racc/visualbasic/cis230ch5/ch5notes1.htm 1/3
1/29/2017 VisualBasicCh.5Notes,page1

youcouldusethecolorselectedbytheuserinyourprogramsincetheuser'sselectionwillbestoredintheColorpropertyofthecommondialog
box.SothestatementfrmForm1.Backcolor=dlgCommon.Colorwouldchangethebackgroundcolorofyourform(named
Form1)tothecolorselectedbytheuser.
InsomecasesyoumustsetthespecialFlagspropertyofadialogboxtoacertainvalueinordertobeabletoaccesstherangeofpossible
valuesforanotherproperty.Forexample,VBneedstodetermineyoursystem'savailablefontsbeforeitallowstheFontpropertytobechanged.
Youcanprovideamoreuserfriendlyinterfacebydeterminingcurrentvaluesofcertainobjectpropertiesandthenpreselectingthosevaluesin
dialogboxesthatappeartotheuser.Seethecodeonpp.180&181.

Objective#3:Writereusablecodeinsubproceduresandfunctionproceduresandcalltheproceduresfromotherlocations.

Programmersshouldstrivetoreusecodewheneverpractical.Thereforeplacingcodethatcanbeusedinmultiplesituationsintogeneral
procedures(asopposedtoeventprocedures)iswise.Forexample,youmayprovideamenuoptionthatprintsaformaswellasacommand
buttonthatprintsaform.Ratherthanduplicatingthenecessarycodethatactuallyprintstheformandplacingthatcodeintotwoareasofyour
project,youcanwriteonegeneralprocedure.Thatgeneralprocedurecanthenbecalledfromseveraleventproceduresasoftenasnecessary.
Tocreateageneralprocedure,youmustdisplaytheCodewindowfortheform.ThenselectAddProcedurefromtheToolsmenu.ChooseSub
astheTypeifyouwishtocreateasubprocedureandchooseFunctionifyouwanttocreateafunctionprocedure.Eitherway,youshould
usuallyselectPrivatefortheScopeoftheprocedure.SelectingPublicasthescopeallowsothermodules(formsandcodemodulestousethe
procedure).
Itisoftennecessaryforaneventprocedure,whichneedstomakeuseofageneralprocedure,topassoneormorevaluestothegeneral
procedure.Thiscouldbedonebydeclaringthevariable(s)tobepassedwithmodulelevelorevenglobalscope.However,oneshouldalways
avoidusinganymoreglobal(ormodulelevel)scopevariablesthannecessary.Thatis,youshouldalwaysuseasnarrowscopesaspossiblewith
allvariables.Thereforetogetaroundthisyoucanpassvaluestothegeneralprocedureasarguments.(Argumentsaresometimescalled
parameterseventhoughthereisatechnicaldifference.Iwillusetheterm"arguments"throughoutthisdiscussionforsimplicity.)
Topassanargument,younameitalongwithitsdatatypewithintheparenthesesthatfollowthenameofthegeneralprocedureinitsheader.
(Theprocedureheaderisthefirstlineoftheprocedure'sdefinition.)Theargumentbeingsenttothegeneralproceduredoesnot(andshouldnot)
havethesamenameasthecorrespondingargumentlistedinthatgeneralprocedure'sheader.Butthedatatypesmustmatch.Ifyoupassmore
thanoneargument,youmustbesuretolisttheminorderthattheyneedtobereceivedandmatchtheirdatatypesaswell.
Youcanpassargumentstoaprocedurebyvalueorbyreference.Passinganargumentbyvaluecausesacopyoftheargumenttobeusedinthe
calledprocedure.Theoriginalargumentwithinthecallingprocedureisnotchangedoraffected.Passinganargumentbyreferenceallowsthe
proceduretopermanentlychangethevalueofthecorrespondingargumentinthecallingprocedure(evenifithasadifferentname).Bydefault,
VBwillpassanargumentbyreference.Ifyouwishtopassanargumentbyvalue,youmustusethekeywordByValbeforetheargument'sname
intheprocedureheader.(ByRefcanbeusedtopassbyreferenceeventhoughitisthedefault.)
VBallowsyoutocreatetwokindsofgeneralprocedures,functionprocedures(orsimplycalledfunctions)andsubprocedures.Thereare
severalkeydifferencesbetweenthetwo.Afunctionprocedureworksalmostidenticallyasasubprocedurehoweverafunctionshouldbeused
whenthereusablecodeisonlymeanttocomputeandreturnonesinglevalue.Thatreturnedvaluecanbeofanydatatypebutthefunction
cannotperformactionslikeaprocedurecan.Usuallyfunctionsaresinglemindedinpurpose.Youmustassignavaluetothenameofthe
functionwithinitsdefinition.Thatvalueisthenreturnedandusedwithinastatementinthecallingprocedure.Thereforeastatementthatcallsa
functionproceduresuchas

intAdd=intAddTwoNums(intNum1,intNum2)

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

alwayslooksdifferentfromastatementthatcallsasubprocedure

AddTwoNumsAndPrintintNum1,intNum2

However,thissubprocedurecallstatementcanalsobewrittenwiththekeywordCallandparenthesessurroundingtheargumentsasin

CallAddTwoNumsAndPrint(intNum1,intNum2)

Anyway,thepurposeoftheprocedureAddTwoNumsAndPrintistocomputeasumandprintthatsumwhilethepurposeofthefunction
intAddTwoNumsisonlytocomputetheactualsum.Subproceduresperformtaskswhilefunctionproceduresareusuallyonlymeantto
computeandreturnaspecificvalue.Notethatyoushouldincludetheproperprefixthatindicatesthereturntypeofafunctioninafunctions
identifier(name).

Objective#4:CreateanexecutablefilethatcanberunfromtheWindowsenvironment.

TocreateanexecutablefileselectMake...fromtheFilemenu.Thiswillnotaffectyouractualproject.Thenewexecutablefilewillhavethe
extension.exeandcanberunfromtheWindowsdesktop.

CIS230HomePage|Mr.Minich'sEducationHomePage|Minich.comWebDesign

http://www.minich.com/education/racc/visualbasic/cis230ch5/ch5notes1.htm 3/3

Potrebbero piacerti anche