Tải bản đầy đủ - 0 (trang)
Chapter 3. Fundamentals of Programming in Visual Basic

Chapter 3. Fundamentals of Programming in Visual Basic

Tải bản đầy đủ - 0trang

Chapter3.Fundamentalsof

ProgramminginVisualBasic

(ThisitemomittedfromWebBookedition)



3.1 VisualBasicControls



42









StartingaNewVisualBasicProgram

ATextBoxWalkthrough

AButtonWalkthrough

ALabelWalkthrough

AListBoxWalkthrough

TheNameProperty

AHelpWalkthrough

Fonts

AutoHide

PositioningandAligningControls



3.2 VisualBasicEvents



60









AnEventProcedureWalkthrough

PropertiesandEventProceduresoftheForm

TheHeaderofanEventProcedure



3.3 Numbers



73









ArithmeticOperations

Variables



IncrementingtheValueofaVariable

Built-InFunctions:Math.Sqrt,Int,Math.Round

TheIntegerDataType

MultipleDeclarations

Parentheses

ThreeTypesofErrors



3.4 Strings



88









VariablesandStrings

UsingTextBoxesforInputandOutput

Concatenation

StringPropertiesandMethods:LengthProperty

andToUpper,ToLower,Trim,IndexOf,and

SubstringMethods

TheEmptyString

InitialValueofaString

OptionStrict

InternalDocumentation

Line-ContinuationCharacter



3.5 InputandOutput



105









FormattingOutputwithFormatFunctions

FormattingOutputwithZones

ReadingDatafromFiles

GettingInputfromanInputDialogBox

UsingaMessageDialogBoxforOutput



UsingaMaskedTextBoxforInput







Summary



127



ProgrammingProjects



128



[Page42]



3.1.VisualBasicControls

VisualBasicprogramsdisplayaWindows-stylescreen(calledaform)with

boxesintowhichuserstype(andinwhichusersedit)informationand

buttonsthattheyclicktoinitiateactions.Theboxesandbuttonsare

referredtoascontrols.Inthissection,weexamineformsandfourofthe

mostusefulVisualBasiccontrols.



StartingaNewVisualBasicProgram

Forourpurposes,VisualBasicprogramsarealsoknownasapplications,

solutions,orprojects.Eachprogramissaved(asseveralfilesand

subfolders)initsownfolder.Beforestartinganewprogram,youshould

useWindowsExplorertocreateafoldertoholdthefoldersforyour

programs.

TheprocessforinvokingVisualBasicvariesslightlywiththeeditionof

VisualBasicinstalledonthecomputer.ToinvokeVisualBasicfroma

computerthathasVisualBasicExpressinstalled,clicktheWindowsStart

button,hoveroverAllPrograms,andthenclickonMicrosoftVisualBasic

2005ExpressEdition.WiththeothereditionsofVisualBasic,hoveroverAll

Programs,hoveroverMicrosoftVisualStudio2005,andthenclickon

MicrosoftVisualStudio2005intheshortlistthatisrevealed.

ThewindowthatappearsafterVisualBasicisinvokedhasamenubar

whosefirstitemis"File".ClickonFile,andthenclickonNewProjectto

produceaNewProjectinputdialogbox.Figure3.1showstheNewProject

inputdialogboxproducedbyVisualBasicExpress.The"Windows

Application"iconshouldbeselectedastheinstalledtemplate.Ifthisisnot

thecase,clickon"WindowsApplication"toselectit.(Theothereditionsof

VisualBasiccontainapaneidentifyingaProjecttype.Youshouldselect

"VisualBasic"astheProjecttype.)



Figure3.1.TheVisualBasicExpressNewProjectinput

dialogbox.

(Thisitemisdisplayedonpage43intheprintversion)



[Viewfullsizeimage]



Note:Thenumberofprojecttypesandiconsshowingwillvarydepending

ontheversionofVisualBasicyouareusing.Figure3.1wascreatedfrom

theExpressEdition.

Thenameoftheprogram,initiallysettoWindowsApplication1,canbe

specifiedatthistime.Sincewewillhaveachancetochangethename

later,let'sjustcalltheprogramWindowsApplication1fornow.Clickonthe

OKbuttontoinvoketheVisualBasicprogrammingenvironment.SeeFigure

3.2.Note:Yourscreenwillresemble,butmaydiffersomewhat,from

Figure3.2.TheVisualBasicprogrammingenvironmentisoftenreferredto

astheIDE(IntegratedDevelopmentEnvironment).



Figure3.2.TheVisualBasicprogrammingenvironment.

(Thisitemisdisplayedonpage43intheprintversion)



[Viewfullsizeimage]



TheMenubaroftheIDEdisplaysthecommandsyouusetoworkwith

VisualBasic.Someofthemenus,likeFile,Edit,View,andWindow,are

commontomostWindowsapplications.Others,suchasProject,Build,and

Debug,providecommandsspecifictoprogramminginVisualBasic.

TheToolbarsholdacollectionoficonsthatcarryoutstandardoperations

whenclicked.Forexample,youcanusethefifthicon,whichlookslikea

stackofthreediskettes,tosavethefilesassociatedwiththecurrent

program.TorevealthepurposeofaToolbaricon,hoverthemousepointer

overtheiconforafewseconds.Thelittleinformationrectanglethatpops

upiscalledatooltip.

InFigure3.2,theMainareacurrentlyholdstheWindowsForm

Designer.TherectangularFormwindow,orformforshort,becomesa

Windowswindowwhenaprogramisexecuted.Mostinformationdisplayed

bytheprogramappearsontheform.Theinformationusuallyisdisplayed

incontrolsthattheprogrammerhasplacedontheform.



[Page44]

TheSolutionExplorerwindowisusedtodisplayvariouspartsofa

program.ThePropertieswindowisusedtochangehowobjectslookand

react.

TheToolboxholdsiconsrepresentingcontrolsthatcanbeplacedonthe

form.ThesecontrolsaregroupedintocategoriessuchasGeneral,Dialogs,

Printing,etc.Figure3.3showstheToolboxaftertheplussigntotheleftof

"CommonControls"hasbeenclicked.Nearlyallthecontrolsdiscussedin

thistextcanbefoundinthelistofcommoncontrols.Thefourcontrols

discussedinthischapteraretextboxes,labels,buttons,andlistboxes.



Figure3.3.TheToolbox'scommoncontrols.



Note:IfyourscreendoesnotshowtheToolbox,movethemouseoverthe

tabmarkedToolboxattheleftsideofthescreen.TheToolboxwillappear.

ThenclickonthepushpiniconinthetitlebarofthetopoftheToolboxto

keepthetoolboxfromslidingoutofthewaywhenthecursorismoved

awayfromtheToolbox.

Textboxes:Youuseatextboxtogetinformationfromtheuser,referred

toasinput,ortodisplayinformationproducedbytheprogram,referredto

asoutput.

Labels:Youplacealabelnearatextboxtotelltheuserwhattypeof

informationisdisplayedinthetextbox.



[Page45]

Buttons:Theuserclicksabuttontoinitiateanaction.

Listboxes:Inthefirstpartofthebook,weuselistboxestodisplaytables

orseverallinesofoutput.Later,weuselistboxestomakeselections.



ATextBoxWalkthrough



1. Double-clickonthetextboxiconintheCommonControlsportionof

theToolbox.Arectanglewithtwosmallsquares,calledsizinghandles,

appearsattheupperleftcorneroftheform.(Youcanalterthewidth

ofthetextboxbydraggingoneofthesizinghandles.)Movethe

mousearrowtoanypointofthetextboxotherthanasizinghandle,

holddowntheleftmousebutton,anddragthetextboxtothecenter

oftheform.SeeFigure3.4.Note:TheTasksbuttonwillbediscussed

laterinthischapter.



Figure3.4.Atextboxwithsizinghandles.



2. Clickanywhereontheformoutsidetherectangletodeselectthetext

box.

3. Clickontherectangletorestorethehandles.Anobjectshowingits

handlesissaidtobeselected.Aselectedtextboxcanhaveitswidth

altered,locationchanged,andotherpropertiesmodified.

4. Movethemousearrowtothehandleinthecenteroftherightsideof

thetextbox.Thecursorshouldchangetoadoublearrow(

).Hold

downtheleftmousebutton,andmovethemousetotheright.The

textboxisstretchedtotheright.Similarly,grabbingthetextboxon

theleftsideandmovingthemousetotheleftstretchesthetextbox

totheleft.Youalsocanusethehandlestomakethetextboxsmaller.

Steps1and4allowyoutoplaceatextboxofanywidthanywhereon

theform.Note:Thetextboxshouldnowbeselected;thatis,its

sizinghandlesshouldbeshowing.Ifnot,clickanywhereinsidethe

textboxtoselectit.

5. Pressthedeletekey,Del,toremovethetextboxfromtheform.Step

6givesanalternativewaytoplaceatextboxofanywidthatany

locationontheform.

6. ClickonthetextboxiconintheToolbox.Thenmovethemouse

pointertoanyplaceontheform.(Whenovertheform,themouse

pointerbecomesapairofcrossedthinlines.)Holddowntheleft

mousebutton,anddragthemouseonadiagonaltogeneratea

rectangle.Releasethemousebuttontoobtainaselectedtextbox.

Youcannowalterthewidthandlocationasbefore.Note:Thetext

boxshouldnowbeselected.Ifnot,clickanywhereinsidethetextbox

toselectit.

7. PressF4toactivatethePropertieswindow.(Youalsocanactivatethe



Propertieswindowbyclickingonit,clickingonthePropertieswindow

iconintherightpartoftheToolbar,selectingPropertiesWindowfrom

theViewmenu,orclickingonthetextboxwiththerightmouse

buttonandselectingProperties.)SeeFigure3.5.Thefirstlineofthe

Propertieswindow(calledtheObjectbox)reads"TextBox1etc."

TextBox1isthecurrentnameofthetextbox.Thefirsttwobuttons

belowtheObjectboxpermityoutoviewthelistofpropertieseither

groupedintocategoriesoralphabetically.Usetheup-anddown-arrow

keys(ortheup-anddown-scrollarrows)tomovethroughthelist.

Theleftcolumngivesthepropertynames,andtherightcolumngives

thecurrentsettingsoftheproperties.Wediscussfourpropertiesin

thiswalkthrough.



[Page46]

Figure3.5.TextboxPropertieswindow.

[Viewfullsizeimage]



Note:IftheDescriptionpaneisnotvisible,right-clickonthe

Propertieswindow,andthenclickon"Description."TheDescription

panedescribesthecurrentlyhighlightedproperty.

8. MovetotheTextpropertywiththeup-anddown-arrowkeys.

(Alternatively,scrolluntilthepropertyisvisible,andclickonthe

property.)TheTextproperty,whichdeterminesthewordsdisplayedin

thetextbox,isnowhighlighted.Currently,thereisnotextdisplayed



intheSettingsboxontheright.



[Page47]

9. Typeyourfirstname.ThenpresstheEnterkey,orclickonanother

property.YournamenowappearsinboththeSettingsboxandthe

textbox.SeeFigure3.6.



Figure3.6.SettingtheTextpropertytoDavid.

[Viewfullsizeimage]



10. ClickatthebeginningofyournameintheTextSettingsbox,andadd

yourtitle,suchasMr.,Ms.,orTheHonorable.(Ifyoumistypedyour

name,youcaneasilycorrectitnow.)Then,pressEnter.

11. Usetheup-arrowkeyorthemousetomovetotheForeColor

property.Thispropertydeterminesthecoloroftheinformation

displayedinthetextbox.

12. ClickonthedownarrowintherightpartoftheSettingsbox,andthen

clickontheCustomtabtodisplayaselectionofcolors.SeeFigure

3.7.Clickononeofthecolors,suchasblueorred.Noticethechange

inthecolorofyourname.



Figure3.7.SettingtheForeColorproperty.



[Page48]

13. HighlighttheFontpropertywithasingleclickofthemouse.The

currentfontisnamedMicrosoftSansSerif.

14. Clickontheellipsis(...)boxintherightpartoftheSettingsboxto

displayadialogbox.SeeFigure3.8.Thethreelistsgivethecurrent

name(MicrosoftSansSerif),currentstyle(Regular),andcurrentsize

(8)ofthefont.Youcanchangeanyoftheseattributesbyclickingon

aniteminitslistorbytypingintotheboxatthetopofthelist.Click

onBoldinthestylelist,andclickon12inthesizelist.Nowclickon

theOKbuttontoseeyournamedisplayedinalargerboldfont.The

textboxwillbelongersothatitcanaccommodatethelargerfont.



Figure3.8.TheFontdialogbox.

[Viewfullsizeimage]



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. Fundamentals of Programming in Visual Basic

Tải bản đầy đủ ngay(0 tr)

×