Tải bản đầy đủ - 0 (trang)
Part VI: Developing Windows Forms 2.0 Applications

Part VI: Developing Windows Forms 2.0 Applications

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

Chapter34.IntroductiontoWindows

Forms2.0

InThisChapter

WindowsFormsBasics

CreatingaWindowsFormsApplication

UsingtheWindowsFormsDesigner

ElementsofGoodUserInterfaceDesign



WindowsFormsisoneofthecorecomponentsofthe.NET

Framework.Itallowsdeveloperstocreateextremelypowerful

andinteractiveapplicationsthatrunonanyWindowsplatform

onwhichthe.NETFrameworkv2.0hasbeeninstalled.Windows

Formsrepresentsaradicalincreaseintimetomarket,easeof

maintenance,andeaseofdeploymentoverotherunmanaged

developmentenvironmentssuchasVisualBasic6and

unmanagedVisualC++.Thisisthefirstofseveralchaptersthat

willhelpturnyouintoaneffectiveWindowsFormsdeveloper.

ThischapterprovidesanintroductiontoWindowsForms,howit

works,andhowyoucanstartcreatingWindowsForms

applicationsusingVisualStudio2005.







WindowsFormsBasics

Atitscore,WindowsFormsisacollectionofclassesallcreated

inthe.NETFramework.Theseclassesprovideacompletely

object-orientedencapsulationofcreatingandmanipulatinguser

interfaceelementssuchasforms,dialogboxes,userinput,

enhancedgraphicaloutput,andmuchmore.

Althoughyoucancreatevirtuallyanytypeofapplicationusing

the.NETFrameworkSDKandNotepad,VisualStudioincludesa

plethoraoftoolsanddesignersthatmakecreatingWindows

Formsapplicationsasmoothandefficientprocessthathas

becomeevenfasterandmorepowerfulwiththecurrentversion

ofVisualStudio.

Figure34.1illustrateshowWindowsFormsfitsinwiththerest

ofthe.NETFramework,includingASP.NETapplications,

WindowsServiceapplications,andconsoleapplications.



Figure34.1.WindowsFormswithinthe.NET

Framework.



Becauseoftheobject-orientednatureofthe.NETFramework

andofWindowsForms,youcanaccomplishalotofthingswith

WindowsFormsthatarevirtuallyimpossiblewithoutit.For

example,youcanuseinheritancetocreateformsthatinherit

fromotherformsandyoucanalsouseinheritancetocreate

yourowncustomcontrolsthatderivefromexistingcontrols.For

example,withonlyafewlinesofcodeyoucouldcreateatext

boxwithyourowncustombehavioraddedtoitwhilereusingall

oftheexistingbehaviorinherentinatextboxcontrol.



WindowsFormsVersusWebForms

Oneofthemostcommontaskswhendesigninganew

applicationisdecidingwhethertouseWindowsFormsorWeb

Forms.Theincrediblepower,flexibility,andscalabilityof

applicationsdevelopedusingthe.NETFrameworkblurstheline

betweentraditionalWindowsapplicationsandwebapplications.



WindowsUpdateIsYourFriend

EversinceWindowsUpdatestartedpushingthe.NET

Framework1.0toWindowsusersthroughitsBITS

backgroundtransfersystem,developersof.NET

applicationshavebeenextremelyhappy.Thereason

isthatbeforethattime,developerscouldnotcount

onusersalreadyhavingthe.NETFrameworkon

theirmachines,sodeploymentofWindowsForms

applicationswasproblematic.With.NET2.0

availablethroughWindowsUpdate,developerscan

actuallymakethebusinessassumptionthatthe

majorityofWindowsXPusersalreadyhavethe.NET

FrameworkinstalledontheirPCs.Thisisa

tremendousadvantageintheWindowsversusweb

argumentintermsofeaseofdeployment.



TherearemanyargumentsforandagainstWindowsForms

applications.MostofthepositivesforWindowsFormsinclude

thefactthataWindowsFormsapplicationcanhaveafarmore

interactiveandgraphicallyrichinterface,whereasWebForms

applicationstendtotakelesstimetobuild.Table34.1takesa

lookatthevariousconcernsforbuildingapplicationsand

indicateswhetherWebFormsorWindowsForms(orboth)

supportsuchfeatures.

Table34.1.DecisionSupportTable:WindowsForms

VersusWebForms

Feature



Deployment



WinForms



Web

Forms



















DeploymentofWindowsFormsapplicationsis

madeeasierusingClickOnce,whereasweb

applicationsareavailableviaawebbrowser

thatvirtuallyallWindowsuserspossess.Web

applicationsarestilloftenconsidered"zero

deployment"applications,however.

TimetoMarket

Inmostcases,webapplicationsofsimilar

complexitytakelesstimetodevelopthantheir

WindowsFormscounterparts.

Interactivity















Thetimeandeffortrequiredtoproducethe

samehighlyinteractiveenvironmentthatisthe

WindowsFormshallmarkinanASP.NET

applicationnegatesASP.NET'stime-to-market

advantage.

RichUserInterface















BothWindowsandWebFormscancreate

extremelyrichandvisuallypleasinguser

interfacesintheirownwayswiththeirown

strengths.However,combiningtheinteractivity

andreactivityofWinFormsherewithGDI+(2D

graphics)capabilitygivesWindowsFormsthe

edge.

Scalability



























BecausebothASP.NETandWindowsFormsare

basedonthe.NETFramework,theycanboth

scaleequallywellwithintheirown

environmentsusingcore.NETtechnologies.

Enterprise/Distributed

Webapplicationscanbeexpandedusingweb

farms,out-of-processstatemanagement,and

muchmore.Bothapplicationtypescanmake

useofCOM+services,remoting,andweb

servicestobuilddistributedsolutions.

Mobile

WindowsFormsapplicationscanbeconverted

torunontheCompactFrameworkfor

PocketPCs,whereasASP.NETapplicationscan

dynamicallyrender"lite"markupdependingon

thefeaturesetofthemobilebrowser.



Thebottomlineisthatalthoughthetwoplatformsareradically

differentintheirpurpose,theyhaveveryfewtechnical

differencesthatwouldswayadeveloperinonedirectionover

theother.Inmostcases,thedecisionofWindowsversusweb

comesdowntothetypeofapplicationbeingcreatedandthe

environmentinwhichitmustbedeployed.Timetomarketand

interactivityaretheonlytwomajorcategoriesinwhichASP.NET

andWindowsFormsevincealargedifferenceinability.Therest

ofthischaptershouldgetyoustartedbuildingWindowsForms



applications.



CreatingaWindowsFormsApplication

CreatingaWindowsFormsapplicationisafairlysimpleprocess.

YoustartoffbyopeningVisualStudio2005andchoosingto

createanewproject.Afterselectingtheappropriatelanguage

fromtheleftsideoftheprojectcreationdialog(assumingyou

havemorethanonelanguageinstalled),clicktheWindowstree

node.Thefollowingprojecttypeswillappear:

WindowsApplicationCreatesanemptyWindowsapplication

withanemptyform.

ClassLibraryCreatesanassemblythatcontainsalibraryof

classes.Youhavecreatedmanyofthesethroughoutthe

courseofthisbook.

WindowsControlLibraryCreatesanassemblythatis

designedtocontainalibraryofcustomWindowsForms

controls.

WindowsServiceCreatesanexecutableapplicationwithout

anyuserinterfacewiththeappropriatecodeandhooksto

runasaservicewithintheServicesControlPanel.

ConsoleApplicationYouhavecreatedcountlessconsole

applicationsifyouhavebeenfollowingalongthroughout

thisbook;createsanexecutableapplicationthatutilizesthe

WindowsCommandPromptconsoleforinputandoutput.

Youalsomightseesomeadditionalprojecttypesdependingon

yourVisualStudioinstallation,buttheoneslistedherearethe

onesthatapplytoWindowsFormsprogramming.

TocreateyourfirstWindowsFormsapplication,clickonthe



"WindowsApplication"template,provideanameforthe

applicationandalocationforyourcode,andclickOKto

continue.Mostofwhatispresentedtoyoushouldseemquite

familiar.RatherthanhavingtheWebFormsDesignerwindow

allowingyoutobuildyourwebapplication,youhaveanimage

ofanemptyformandaToolboxfullofWindowsFormstools

thatlookssomethingliketheimageshowninFigure34.2.



Figure34.2.AnemptyWindowsForms

application.



[Viewfullsizeimage]



Thenextsectionwillteachyouthebasicsofbuildingapowerful

userinterfaceusingtheWindowsFormsDesigner.



UsingtheWindowsFormsDesigner

TheWindowsFormsDesigneristheinteractivetoolusedto

graphicallylayoutandconfiguretheelementsofyouruser

interface.Youusethisdesignertocreateandmanipulateforms

aswellastodesignandlayoutthecontrolsonthoseforms.

TogetstartedusingtheWindowsFormsDesigner,draga

control(anysimplecontrolshoulddo)ontoaform.Asyouare

draggingyou'llseeasmalloutlinethatindicatesthepointat

whichthecontrolwillbeinserted.Whenyouletgoofthe

control,itwillappearcompletelyatthedesignatedinsertion

point.

Whenacontrolisonthesurfaceofaform,youcanconfigureall

ofthecontrol'spropertiesusingthePropertieswindow.By

default,thiswindowshowsupinthebottomrightoftheVisual

StudioscreenbelowtheSolutionExplorerwindow.Ifthe

windowisnotvisible,youcanmakeitvisiblebyselectingView,

PropertiesWindow.YoucanalsousethehotkeyCtrl+W,P.This

willopenthePropertieswindowifithasbeenclosedandwill

thensetthefocustothatwindow.InsidethePropertieswindow

youcanconfigurevirtuallyeveryaspectofacontrol.Ifyouclick

thelightning-bolticonfromwithinthePropertieswindow,you

canalsoseealistofalltheeventsexposedbyagivencontrol

(suchasaneventforwhenthecontrolisclicked,doubleclicked,andsoon).Ifyoudouble-clickanemptyspacenextto

anevent,youcancreateaneventhandlerforthateventon

thatcontrol.

Thelistofpropertiesthatbelongtoagivencontrolisspecificto

thatcontrol,andmanycontrolpropertieswillbecoveredin

Chapter35,"TheWindowsFormsControlLibrary."Themost

importantthingsthatyouwillusetheformsdesignerforare

navigatingcontrolstructures,whichcanbemadesignificantly

easierbytheDocumentOutlinewindow;aligningandjustifying



controlsusingthenewSnapLinesfeature;andfinally,youwill

beusingthedesignertomakesurethatasthehostformgrows

andshrinks,thesizeandlayoutofthecontrolsontheform

adjustaccordingly.Youcanperformallofthesetasksusingthe

designerandwithouthavingtowriteasinglelineofcode.



UsingtheDocumentOutlineWindow

TheDocumentOutlinewindowisanextremelypowerfultool

thatallowsadevelopertorapidlylocateanindividualcontrol

thatmightbenesteddeepwithinothercontrolsonaform.

Despiteitspower,thiswindowisoftenoverlookedoreven

forgottenbymanydevelopers.



Tip

Evenifyoudon'tuseitallthetime,youshouldget

inthehabitofmakingsurethattheDocument

Outlinewindowhasbeenopenedatthebeginningof

aproject.Thatwayitwillappearasatabnextto

SolutionExplorer.Withitsittinginavisiblelocation

inyourworkstation,youaremorelikelytonoticeit

andmakeuseofit.Withsimpleinterfacesitmaybe

completelyunnecessary,butwhenyoustartcreating

complexinterfaceswithmanylevelsofnested

controls,youmaywonderhowyoumanagedto

survivewithoutit.



Thiswindow,showninFigure34.3,displayscontrolsinatree

sothatyoucangetaquicklistofallcontrolsontheformas

wellasareferenceofwherethosecontrolsallareinrelationto

eachother.Whenyouhavemanylevelsofnesting,itcan



becomeextremelydifficultorevenimpossibletoproperlyclick

onandselectchildcontrolsusingjustthevisualdesigner.Ifyou

runintothatsituation,youcanusetheDocumentOutline

windowtoquicklyfindandselectthecontrolyouneed.



Figure34.3.TheDocumentOutlinewindow.



LiningUpControlswithSnapLines

OneofthemosthelpfulandpowerfulnewfeaturesoftheVisual

Studio2005FormsDesigneristheuseofSnapLines.SnapLines

areanewfeaturethatallowyoutovisuallyaligncontrolswhile

maneuveringthemaroundthedesignsurface.

WithpreviousversionsofVisualStudio,oneofthemost



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

Part VI: Developing Windows Forms 2.0 Applications

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

×