Tải bản đầy đủ - 0 (trang)
Chapter 14. Using Windows Forms in VSTO

Chapter 14. Using Windows Forms in VSTO

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

Introduction

Officehasauserinterfacethathasbeendesignedtomakeitas

easyaspossibleforanendusertoaccessthefunctionality

providedbyeachOfficeapplication.Buttheapplicationyouare

writingthatisintegratedwithOfficewillhaveitsownvery

specificuser-interfacerequirements.Theapplicationyouwrite

willhaveuser-interfaceneedsthatarenotmetbythedefault

Officeuserinterface.

InpreviousversionsofOffice,VisualBasicforApplications

(VBA)providedtheabilitytoshowUserFormstomeetyour

applicationuser-interfacerequirements.Youcouldalsouse

customActiveXcontrolsonthedocumentsurface.VSTOadds

WindowsFormscontrolsupporttoOfficetomeetyouruserinterfaceneeds.



MovingfromActiveXtoWindowsForms

WhenwestarteddesigningVSTO,beingabletobuild

applicationsthatextendedthedefaultOfficeuserinterfacewas

oneofourprimarygoals.Wealsowantedtoensurethat

developerswritingmanagedcodewouldnothavetorelyon

ActiveXcontrolstodoso;.NETdeveloperswanttouseWindows

Formscontrols.Toaddresstheserequirements,theteamcame

upwithadesigntointegrateWindowsFormsdeeplyintoOffice.

ThevisionwastoallowyoutouseWindowsFormscontrolsand

formsinalltheplacesyoucoulduseActiveXcontrolsandUser

FormsinpreviousversionsofOffice.Wealsowantedtomake

thedesignandcodingexperiencesimilartothatofatraditional

WindowsFormsapplication.

ThischaptercovershowtouseWindowsFormscontrolsinyour

VSTOapplications.YoucanuseWindowsFormsinVSTOin



threebasicways:

1. YoucanputaWindowsFormscontrolonthedocumentor

spreadsheetsurface.

2. YoucandisplayacustomWindowsFormsformasamodal

ormodelessdialogbox.

3. YoucanputWindowsFormscontrolsintheDocument

ActionstaskpaneusingtheActionsPanefeatureofVSTO.

Wecoverthefirsttwowaysinthischapter.Thischapteralso

covershowtocreatecustomusercontrolsthatcanbeusedto

providesolutionstosomeoftheshortcomingsoftheWindows

FormssupportinVSTO.ThethirdwaytouseWindowsFormsin

VSTOusingcontrolsintheDocumentActionstaskpaneis

coveredinChapter15,"WorkingwiththeActionsPane."



WhentoUseWindowsFormsControlsonthe

DocumentSurface

VSTOenablesdeveloperstoputWindowsFormscontrolsonthe

documentsurface.Justbecauseyoucanputacontrolontothe

documentsurfacedoesnotnecessarilymeanthatitisagood

ideaforyourparticularapplication.Whenshouldyouusea

controlonadocumentasopposedtousingaform,anintrinsic

Officeuser-interfaceelementsuchasacellorahyperlink,a

custommenucommandortoolbarbutton,aSmartTag,orthe

actionspane?

Thinkabouthowyouexpectthedocumentorspreadsheettobe

usedandhowyouwanttoextendtheinterface.Maybeyouare

goingtouseanExcelspreadsheetasafrontendtocorporate

data.ManystockbrokersuseExcelastheirprimaryinputand

displaymechanismwhentrading,forexample.Inthisscenario,

thespreadsheetisveryrarelye-mailedorprinted,sochanging



thespreadsheetinterfacetomeettheapplicationrequirements

makesalotofsense.PuttingaWindowsFormsbuttoncontrol

onthesurfaceofthedocumentmeetstherequirementof

makingthespreadsheetmoreinteractiveandprovidesobvious

actionsthatareavailabletotheuserofthespreadsheet.Figure

14.1showstwoWindowsFormsbuttonsthathavebeenplaced

onaspreadsheetonethatrefreshesthestockquotesandthe

otherthattradesaparticularstock.



Figure14.1.TwoWindowsFormscontrolsona

spreadsheet.



[Viewfullsizeimage]



Sometimesyouwillhavedatathatneedstobeeditedwitha

moreeffectiveuserinterfacethanOfficeprovides.Agood

exampleofthisisdateinput.ExcelandWordprovidearich

mechanismtodisplaydatesbutdonotprovideaneasy-to-use

mechanismforenteringdatesotherthanbasictextinput.

WindowsFormsprovidesaDateTimePickercontrolthatmakesit

easyforausertoenteradate.Combiningthedateentry

interfaceprovidedbytheDateTimePickerandthedisplay

capabilitiesofExcelorWordresultsinamoreeffectiveuser

interface.

YoucouldintegratetheDateTimePickerintoyourworkbook,as

showninFigure14.2.Here,wehaveaddedaDateTimePicker

controlforeachcellcontainingadate.TheDateTimePicker



providesacombo-boxdrop-downlistwithacalendarthatthe

usercanusetopickadifferentdate.



Figure14.2.DateTimePickercontrolsona

spreadsheet.



[Viewfullsizeimage]



TheDateTimePickermaybebetterusedintheDocument

Actionstaskpanethanonthedocumentsurface,however.The

firstproblemyouwillencounterwithasolutionsuchastheone

showninFigure14.2iswhatyouwillputinthespreadsheetfor

thevaluesofthecellscoveredbytheDateTimePickercontrols.

Itwouldseemreasonablethatthecellcoveredbyaparticular

DateTimePickercontrolshouldcontainthedatevaluebeing

representedbythecontrol.Thisway,thedatevalueforthatcell

canbeusedinformulasandcanbefoundwhentheuser

searchesthespreadsheetwithExcel'sFindcommand.

ThesecondproblemisthatifyouputtheDateTimePickeronthe

documentsurface,thecontroldoesnotautomaticallysaveits

stateintotheExcelworkbookwhenthedocumentissaved.So,

ifinaparticularsessiontheuserselectsseveraldatesandthen

savesthedocument,thenexttimetheuseropensthe

workbook,alltheDateTimePickerswillresettotoday'sdate.



Youwilllosethedatetheuserpickedinthelastsessionunless

youwritecodetosynchronizetheDateTimePickerwiththecell

valuecoveredbyitonstartupoftheExcelworkbookand

whenevertheDateTimePickerorunderlyingcellvaluechanges.

AthirdproblemiskeepingtheDateTimePickercontrolslooking

liketherestoftheworkbookformatting.Iftheuserchanges

thefontoftheworkbook,thecontrolsembeddedinthe

documentwillnotchangehisfont.Printingisalsoanissue

becausethecontrol,repletewithitsdrop-downcombowidget,

willbeprinted.Inaddition,theuserwilllikelywanttoaddand

removerowsinthelistofstocks,whichmeansthatyouwill

havetoaddandremoveDateTimePickercontrolsdynamicallyat

runtime.

Althoughitispossibletoworkthroughtheseissuesandachieve

areasonablesolution,theactionspanemaybeaneasier

mechanismtouse.TheactionspanecanshowWindowsForms

controlsalongsidethedocumentintheDocumentActionstask

paneratherthaninthedocument.Whenevertheuserofyour

workbookhasadatecellselected,forexample,theDocument

ActionstaskpanecanbedisplayedwiththeDateTimePickerinit

toallowtheusertopickadate,asshowninFigure14.3.

Chapter15,"WorkingwiththeActionsPane,"discussesthe

actionspane.



Figure14.3.UsingtheDateTimePickercontrolin

theDocumentActionstaskpane.



[Viewfullsizeimage]



WhentoUseaModalorModelessWindows

FormsForm

AnotherwaytouseWindowsFormsinanOfficeapplicationisto

useastandardWindowsFormsformshownasadialogbox.You

couldhandletheBeforeDoubleClickeventfortheworksheet,for

example,andifacellcontainingadateisdouble-clicked,you

coulddisplayacustomWindowsFormsform,asshownin

Figure14.4.



Figure14.4.DisplayingaWindowsFormsdialog

boxwhentheuserdouble-clicksacell.



[Viewfullsizeimage]



Thisapproachisalsoquiteusefulifyouwanttoensurethat

certaininformationisfilledinbeforetheuserstartsworking

withadocument.Youmightwanttodisplayawizardduringthe

creationofadocumentthatfillsincertainportionsofthe

document,forexample.

AchoiceyoumustmakewhenusingWindowsFormsasshown

inFigure14.4isthemodalityoftheform.Amodalformmust

beinteractedwithanddismissedbyclickingtheOK,Cancel,or

Closebuttonbeforetheusercangetbacktoeditingthe

document.AmodelessWindowsFormscanfloatabovethe

documentandstillallowtheusertointeractwiththedocument

eventhoughtheformhasnotyetbeenclosed.Whenusinga

modelessWindowsFormsdialogbox,notethatanOffice

applicationcanentercertainstateswhereyourmodelessdialog

boxcannotbeactivated.Ifanothermodaldialogboxis

displayed,forexample,usersmustdismissthemodaldialog

boxbeforetheycaninteractwiththemodelessdialogbox

again.Cell-editingmodeinExcelalsoaffectsmodelessdialog

boxes.IftheuseriseditingacellvalueinExcel,shecannot

activatethemodelessformuntilsheleavescell-editingmode.



Listing14.1showsaVSTOExcelcustomizationthatdisplaysa

simplemodelessform.Themodelessformhasabuttonthat,

whenclicked,showsamessagebox.



Listing14.1.AVSTOExcelCustomizationThat

DisplaysaModelessForm



PublicClassSheet1

PublicWithEventsbtn1AsButton

Publicform1AsForm

PrivateSubSheet1_Startup(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMe.Startup

btn1=NewButton()

form1=NewForm()

form1.Controls.Add(btn1)

form1.Show()

AddHandlerGlobals.ThisWorkbook.BeforeClose,_

AddressOfThisWorkbook_BeforeClose

EndSub

PrivateSubbtn1_Click(ByValsenderAsObject,_

ByValeAsEventArgs)_

Handlesbtn1.Click

MsgBox("Youclickedme.")

EndSub

PrivateSubThisWorkbook_BeforeClose(ByRefCancelAsBoolean)

form1.Close()

EndSub

EndClass



NotethatusingtheActionsPanefeatureofVSTOisoftenan

easierwaytoachieveamodelessresult,becauseitprovidesall

thebenefitsofamodelessform,withtheadditionoftheability

todockwithintheOfficewindowspace.



AddingWindowsFormsControlstoYour

Document

OneofthekeydesigngoalsforVSTOwastokeepthedesign

experienceasclosetoexistingWindowsFormsdevelopmentas

possible,andaddingWindowsFormscontrolstothedocument

isakeytenetofthisgoal.Thegreatthingaboutaddingcontrols

tothedocumentorspreadsheetisthatyoureallydonothave

tothinkaboutit,becausemostofthedesignexperienceis

almostidenticaltothatofcreatingaWindowsFormsform.

Therearesomedifferencesintheexperience,however,andwe

examinetheminthissection.

WhenyoucreateanewprojectbasedonanExcelworkbookor

Worddocument,VSTOcreatesaprojectandautomaticallyloads

theExcelorWorddocumentsurfaceintoVisualStudioto

provideadesignsurfaceforyoutodraganddropcontrolsonto.

Itiseasiertopinthetoolboxtomakeitdocktothesideof

VisualStudiowindow,becauseitisdifficulttodraganddrop

fromthetoolboxontoWordorExcelwhenitisinitsdefault

autohidemode.Why?Whenthetoolboxshowsitself,it

obscuresquiteabitoftheleftsideofthedocumentor

spreadsheet.Whenyoudraganddropacontrolontothe

documentsurface,thetoolboxdoesnotautohideandgetoutof

thewayuntilthedraganddropisover.



ModesforAddingControls

VSTOprovidesthreemodesforaddingcontrolstothedocument

surface:

DragginganddroppingThisinvolvesselectingthecontrol

fromthetoolboxanddraggingitontothedocumentor



worksheet.Thismethodcreatesadefault-sizecontrolon

thedocumentandprovesparticularlyusefulforadding

controlsthattendtobeasetsize,suchasbuttons.Figure

14.5showsthismode.



Figure14.5.DraganddropofaButtoncontrol

fromthetoolboxtoanExcelworksheet.



DrawingClickingacontrolinthetoolboxtoselectitand

thenmovingyourmousepointeroverthedocumentor

spreadsheetchangesthecursortothestandarddraw

cursor.Inthismode,youcanclickanddragarectangle,

therebydrawingthecontrolontothedocumentor

spreadsheet.Figure14.6showsthismode.



Figure14.6.DrawingaPictureBoxcontrolona

Worddocument.



Double-clickingDouble-clickingacontrolinthetoolbox

causesacontroltobeaddedatthecurrentinsertionpoint

inthedocumentorspreadsheet.TheinsertionpointinWord

behavesquitedifferentlyfromthewayitbehavesExcelnot

surprising,giventheflow-basednatureofadocument

comparedwiththegridofaspreadsheet.Double-clickinga

controlinthetoolboxinaWordVSTOprojectinsertsthe

controlatthecursorinthedocument.Double-clickinga

controlinthetoolboxinanExcelVSTOproject,however,

insertsthecontrolatthecenterofthespreadsheet.



ControlsThatAreNotintheControlToolbox

AnumberofWindowsFormscontrolsdonotshowupinthe

controlstoolboxforExcelandWordprojects.Thesecontrols

werepurposelyexcludedbecauseofknownissuesinusing

themonthedocumentsurface.Someoftheseissuesarepurely



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

Chapter 14. Using Windows Forms in VSTO

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

×