Tải bản đầy đủ - 0 (trang)
Chapter 35. The Windows Forms Control Library

Chapter 35. The Windows Forms Control Library

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

controls,whetherthatlanguageisC#,VB.NET,orevenDelphi

for.NET.

WithVisualStudio2005,thetoolboxofWindowsFormscontrols

hasgrownsignificantly.Newcontrolshavebeenaddedandold

controlshavebeenmodifiedandimproved.Thischaptertakes

youthroughawhirlwindtourofeverysinglecontrolavailablein

theVisualStudio2005WindowsFormscontrolToolbox.Asyou

progressthroughthebooktootherWindowsFormschapters,

manyofthesecontrolswillbeusedagainwithmoredetailed

explanationsandcodesamples.







TheCommonControlsToolbox

TheCommonControlsToolboxcategoryisessentiallya

"Miscellaneous"category.Itcontainsthecontrolsthatyouwill

typicallyfindineverysingleWindowsFormsapplicationsuchas

buttons,textboxes,checkboxes,radiobuttons,andsoon.This

sectionprovidesanoverviewofeachofthesecontrolsandwhat

theydo,aswellashowandwhentheyshouldbeused.



TheButtonControl

Thebuttonisthedefactostandardforuserinteractivity.Ifa

userwantstoconfirmchanges,openanewwindow,startor

completeatask,orvirtuallyanyothermajortask,thattaskis

oftenrepresentedbyaButtonofsomekind.Buttonscanbe

standardbuttonsortheycanhaveaflatappearanceorevenbe

madeupofimages.Mostoftheworkdonebybuttonsis

accomplishedthroughtheClickevent.



TheCheckBoxControl

AcheckboxisagraphicalexpressionofaBooleanvalue.Ifthe

boxischecked,theunderlyingvalueistrue.Iftheboxisnot

checked,theunderlyingvalueisfalse.Youcanrespondto

eventssuchaswhenthecheckedstatusoftheboxchanges,

andsoon.Checkboxescanbedata-bounddirectlytoany

Booleanvalue.



TheCheckedListBoxControl

TheCheckedListBoxcontrolisanextremelypowerfulandhandy



tool.Itdisplaysalistofitemsinmuchthesamewayasa

ListBoxcontrol,andwhenanitemisselected,theCheckBoxcontrol

associatedwiththatitembecomeschecked.Youcanobtainthe

listofitemscurrentlyselectedinthecontrolwiththe

SelectedItemsproperty.Ifyouneedtopresenttheuserwith

severalcheckboxesandyouwantthosetobeformattedinan

organizedlist,thiscontrolwillhelp.



TheComboBoxControl

TheComboBoxisanothercontrolthatyouwillseeinjustabout

everyWindowsFormsapplicationsomewhere.Itsresponsibility

istopresenttheuserwithalistofoptionsandallowherto

selectone.YoucansettheComboBox'sDropDownStyletocontrolits

behavior.TheSimplemodeallowstheusertomanuallytypein

thetextportionwiththelistportionoftheComboBoxremaining

visible.TheDropDownmodeisthesameasSimple,exceptthatthe

usermustclickthedown-arrowtorevealtheitemlist.Finally,

theDropDownListmodeisoneofthemostcommonmodesand

doesn'tallowtheusertomanuallytypeanything;shemust

selectanitemfromthelist.Ifauserneedstoselectasingle

value(orprovidehisown)fromalistofvalues,theComboBox

controlistherighttoolforthejob.



TheDateTimePickerControl

TheDateTimePickerisahandycontrolthatlookssimilartoa

ComboBoxonthesurface,butwhenyouclickthedownarrowon

thiscontrol,acalendarappears.Thiscalendarallowsyouto

navigatemonthbymonthoradvanceorreverseyears.When

theuserclicksonaspecificdate,thatdatebecomestheValue

propertyofthecontrol,whichisoftypeDateTime.Today'sdate

showsuphighlightedwithaboxaroundit.Theprogrammercan

alsochoosetheformatinwhichtheselecteddateappearsfor



maximumflexibility.Figure35.1showsaDateTimePickerinaction.



Figure35.1.ADateTimePickercontrol.



TheLabelControl

Labelsareprettysimplecontrols.Ifyouwanttoincludesome

textonaformthatisjusttherefordecorationanddoesn'tdo

muchbeyondthat,theLabelisthecontrolyouneed.Justputit

whereyouwant,setthemargins,padding,justification,

foregroundcolor,backgroundcolor,andtheTextproperty,and

you'rereadytogo.



TheLinkLabelControl

TheLinkLabelcontrolworksverymuchlikethestandardLabel

control,exceptthatitrenderslikeanHTMLhyperlink.The



defaultforegroundcoloristhesamebluethatmostbrowsers

useasthedefaulthyperlinkcolor.TheLinkLabelhasaLinkClicked

eventthatyoucanusetorespondtowhenauserclicksonthe

activetextofthelabel.Thefollowingfewlinesofcodeareused

asaneventhandlerforaLinkLabelwiththeTextpropertyof"Go

toSAMSPublishing":



privatevoidlinkLabel1_LinkClicked(objectsender,LinkLabelLin

{

Processp=newProcess();

p.StartInfo=

newProcessStartInfo("http://www.samspublishing.com");

p.Start();

}



Inthreesimplelinesofcode,youcanhaveauserclickalink

andusethecurrentdefaultbrowsertoopenalinktoanyURL.

Youdon'thavetousetheLinkLabelforopeningwebpages,

however.Itisideallysuitedforsupplyingpop-upsofhelp

informationandlaunchingsmallsubforms.



TheListBoxControl

TheListBoxisprettyself-explanatory.Itisaboxthatholdsalist

ofitems.Youcanloadthelistofitemsprogrammatically,at

designtime,orthroughanyofthedata-bindingfeaturesof

WindowsForms.Youcanaccessthelistofitemsthroughthe

Itemsproperty,andyoucangettheselecteditemoritemswith

theSelectedItemandSelectedItemspropertiesrespectively.Youcan

alsoobtainthenumericalindicesofselecteditemsusingthe

SelectedIndicesproperty.Youtypicallyusethiscontrolifyouneed

topresenttheuserwithalistofoptionsandallowthemto

selectoneormoreofthoseitems.



TheListViewControl

TheListViewtakestheconceptofaListBoxandaddsquiteabit

ofadditionalfunctionality.Thereissomuchpowerinthis

controlthatinpreviousversionsofWindowsForms,developers

oftenpreferredthiscontrolovertheDataGridfordisplayinggrids

ofdata.TheListViewsupportsmultipledisplaymodesthatthe

developercanswitchprogrammaticallyortheusercanselect

them(ifthedeveloperprovidesthatability).Thesemodesare:

LargeIcon,Details,SmallIcon,List,andTile.TheLargeIconand

SmallIconmodesaregraphicaldisplaymodesthatdisplayanicon

aswellasthetextofthelistitem.TheDetailsmodedisplaysthe

listinasetofrowsandcolumnsintabularfashion.Thefirst

columncontainsthelistitem'sTextproperty,whileeach

additionalcolumnrepresentsoneofthatitem'ssubitems.List

modejustdisplaysthelistitemsinasimplelistformatwithno

additionalinformation.Youcanspecifytheimagesusedforthe

ListViewusingtheSmallImageList,StateImageList,andLargeImageList

properties.

OneofthenewfeaturesoftheListViewthatwasaddedforthe

2.0versionofWindowsFormsistheuseofgroups.TheListView

controlwillnowallowyoutogrouplistitemsanddisplaygroup

headersinthelist.TheLargeIcon,SmallIcon,Tile,andDetails

modessupportthedisplayoflistitemgroups.



TheMaskedTextBoxControl

TheMaskedTextBoxcontrolisanothernewadditionwiththe2005

setofcontrols.ThisTextBoxallowstheprogrammertodefinea

maskthatindicatestheallowedinput.Whenauserstarts

typinginamaskedtextbox,theinputwillsimplyberejectedif

itdoesn'tmatchthemask.Thismeansthatdeveloperscanuse

theMaskedTextBoxtoallowonlynumericdataoronlyphone

numbersthatmatchaspecifiedformat.



WhenyousettheMaskpropertyoftheMaskedTextBoxcontrol,you

willseetheInputMaskdialogshowninFigure35.2.Thisdialog

letsyouselectfromanumberofusefulpre-createdmasks

(suchasphonenumber,e-mailaddress,andsoon),oryoucan

pickthemaskanddefineyourownpatternusingmask

rules.



Figure35.2.TheInputMaskdialogfora

MaskedTextBoxcontrol.



TheMonthCalendarControl

TheMonthCalendarcontrolisessentiallylikeaDateTimePickerexcept

thatthereisnotext-entryportion.Thecalendarisalways

visibleanduserscanusethecontrolsonthecalendarto

navigateforwardandbackwardintime.Today'sdateis



highlightedjustasitiswiththeDateTimePickercontrol.



TheNotifyIconControl

TheNotifyIconcontrolisextremelypowerfulandhaseven

receivedabitofaboostinWindowsForms2.0.This

component,whenyoudragitontoyourform,allowsyouto

displayaniconintheWindowssystemtraywhereyoutypically

seeiconsforyourvirusscanner,instantmessagesystem,and

anyotherbackgroundapplicationsyoumightberunning.

YoucansettheIconpropertyofthecontrolatdesigntimeor

programmaticallyatruntimetohavetheiconchangedepending

onthestateofyourapplication.Youcanevencreateatimerto

swaptheiconeveryfewmillisecondstocreateablinkingor

flashingicon.

Somethingnewwith2.0istheabilitytoworkwiththeWindows

XPnotificationballoons.Theseballoonsshouldbefamiliarto

anyonewhousesWindowsXPWindowsUpdatedisplaysthem

whenupdatesarereadytodownload.UsingtheShowBalloonTip

method,youcanquicklycreateacompellingnotificationfrom

thesystemtrayliketheoneshowninFigure35.3.



Figure35.3.Usingballoontipswiththe

NotifyIconcomponent.



TheNumericUpDownControl

TheNumericUpDownisasimpletextcontrolthatallowsusersto

enteranumberoruseacombinationofupanddownarrowsto

increaseanddecreasethenumber.Youcansettheamountthat

isincrementedbythearrowsusingtheIncrementpropertyand

youcansetthecurrentnumberusingtheValueproperty.When

usersneedtoenternumericdataintoatextbox,thiscontrolis

oftenmoreappropriatethanastandardTextBoxcontrolorevena

MaskedTextBoxcontrol.



ThePictureBoxControl

ThePictureBoxcontrolisresponsiblefordisplayinganimage.

Whereveryouplacethecontrolyoucanhaveanimage

displayed.Thisimagecanbesetdynamicallyatruntimeorit

canbeloadedfromanynumberoffileformatssuchasbitmap,

JPG,PNG,andsoon.Thedeveloperhascontroloverthe

alignment,scale/stretch,position,andmuchmore.Imagescan

evenbeloadedatdesigntimefromprojectresourcesusingjust

thedesignerthistaskusedtorequireadditionalcodingin

previousversionsofWindowsForms.



TheProgressBarControl

TheProgressBarisafairlysimplecontrolthatgraphicallydisplays

progress.AfteryousettheMaximum,Minimum,andValueproperties,

theprogressbarwillgraphicallydisplaythepercentageof

completion.Progressbarsareusedprimarilytoprovidetheuser

withagraphicalindicationthatsomethingistakingplaceinthe

backgroundandcouldpotentiallybealong-runningtask.The

new2.0ProgressBarusesthefamiliarWindowsXP-styleprogress

bar.Aseachnewitemappearswithinthebar,itanimatesitself



intothebarbyspreadingoutvertically.Youcanseethisifyou

increasetheMarqueeAnimationSpeedpropertyandthenslowly

changetheValuepropertyoftheProgressBar.



TheRadioButtonControl

ARadioButtonisacontrolthatworksinawaythatissimilartoa

CheckBox.Radiobuttonsaresmallcirclesthathaveadotinthem

iftheyareselectedandarehollowotherwise.Radiobuttonsare

typicallyusedingroupstoallowausertoselectonlyoneoption

fromalistofoptions.



TheTextBoxControl

TheTextBoxcontrolisasimpleinputcontrolthatallowsusersto

enterfree-formtextineithersingleormultilineinputmodes.As

withallstock.NETcontrols,theTextBoxcontrolsupportsUnicode

input,souserstypinginlanguagesthathavemorethan255

characters,suchasChineseorHindi,willbeabletouseallof

the.NETcontrolswithoutthedeveloperhavingtodoany

additionalwork.



TheRichTextBoxControl

TheRichTextBoxcontrolworksinawaythatisverysimilartothe

TextBoxcontrol,butallowsthetexttohaveadditionalproperties

suchasvaryingfonts,colors,sizes,andstylessuchasbold,

italic,orunderlined.TheRichTextBoxcontrolisoften

underestimated.Itisactuallyasmallwordprocessorbundled

intoasinglecontrol.Inadditiontostandardformatting,this

controlalsosupportsbulletedlistsandothermoreadvanced

wordprocessingfeatures.Youcanalsosaveandloadthe



contentsofaRichTextBoxcontrol.Theonlyrealworkthe

developerneedstodoisprovidetheinterfacethatchangesthe

propertiesoftheselection.ThisisthesamemethodMicrosoft

Wordusestochangetextattributes.TheRichTextBoxcontrolhas

propertiessuchasSelectionFontandSelectionColortochangethe

currentfontandcolorproperties.WhenyouexaminetheText

propertyofthecontrol,youwillgettherawtextwithoutthe

formatting.



TheToolTipControl

TheToolTipcontrolisapowerfulnewadditiontothesetof

controlsavailableinWindowsForms.TheToolTipcontrolisone

ofthe"provider"typesofcomponents.Whenyouplaceitona

form,youaredefiningatemplateforhowtooltipsshouldbe

displayed,notthetooltipitself.WhentheToolTipisontheform,

allothercontrolsonthatformwillgainanadditionalproperty

thatlookslikeToolTiponToolTip1.UsingtheToolTipcontrol,you

canspecifytheanimationspeedofthepop-uptip,youcan

specifytheiconthatwillbedisplayed,andyoucaneven

customizetheforegroundandbackgroundcolorsusedto

displaythetooltip.Thesetooltipsaremuchbetterlookingthan

theonesthatwerepossibleusingpreviousversionsofWindows

Forms.AtooltipwithaniconisdisplayedinFigure35.4.



Figure35.4.TheToolTipcontrolinaction.



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

Chapter 35. The Windows Forms Control Library

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

×