Tải bản đầy đủ - 0 (trang)
Chapter 16. Working with Smart Tags in VSTO

Chapter 16. Working with Smart Tags in VSTO

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

IntroductiontoSmartTags

TheSmartTagsfeatureofWordandExcelenablesyouto

displayapop-upmenuwithactionsforagivenpieceoftextina

documentorspreadsheet.ASmartTagcouldrecognizestock

symbols(suchastheMSFTstocksymbol)anddisplayasetof

actionsthatcanbetakenforthatsymbol,forexample.When

WordfindsapieceoftextthataSmartTaghasrecognized,it

displaysareddottedunderlineundertherecognizedtext.Ifthe

userhoversoverthetext,apop-upmenuiconappearsnextto

thecell,asshowninFigure16.1.Iftheuserclicksthepop-up

menuicon,amenuofactionsdisplaysfortherecognizedpiece

oftext,asshowninFigure16.2.Whenanactionisselected,

WordcallsbackintotheSmartTagtoexecutetheaction.



Figure16.1.SomerecognizedtextinWord



Figure16.2.DroppingdowntheSmartTagmenu

inWord.



WhenExcelrecognizesaSmartTag,itdisplaysalittletriangle

inthebottom-rightcorneroftheassociatedcell.Iftheuser

hoversoverthecell,apop-upmenuiconappearsnexttothe

cell;theusercanclickthisicontodropdownamenuofactions

fortherecognizedpieceoftext.Figure16.3showsanexample

menu.Whenanactionisselected,Excelcallsbackintothe

SmartTagtoexecutetheaction.



Figure16.3.DroppingdowntheSmartTagmenu

inExcel.



Figure16.4showssomeadditionaldetailaboutthedrop-down

listthatappearsforrecognizedtext.Atthetopofthedropdownlist,thenameoftheSmartTagdisplays,alongwiththe

textthatwasrecognized.Thenextsectionofthemenushows

actionsthatareavailableforthegivenSmartTag.This

particularSmartTag,calledFinancialSymbol,hasfouractions

associatedwithit.Thebottomsectionofthemenuprovides

Word-orExcel-specificoptionsfortheSmartTag.



Figure16.4.TheSmartTagmenu.



ConfiguringSmartTagsinWordandExcel

SmartTagsinWordaremanagedfromtheSmartTagstabof

theAutoCorrectOptionsdialogbox,showninFigure16.5.The

SmartTagstabcanbedisplayedbychoosingAutoCorrect

OptionsfromtheToolsmenu.Here,theusercanturnonand

offindividualSmartTags,aswellascontrolotheroptions

relatingtohowSmartTagsdisplayinthedocument.



Figure16.5.Word'sSmartTagstabinthe

AutoCorrectdialogbox.



SmartTagsinExcelaremanagedfromtheSmartTagstabof

theAutoCorrectdialogbox,asshowninFigure16.6.TheSmart

TagstabcanbedisplayedbychoosingAutoCorrectOptionsfrom

theToolsmenu.Here,theusercanturnonandoffindividual

recognizers,aswellascontrolotheroptionsrelatingtohow

SmartTagsdisplayintheworkbook.



Figure16.6.Excel'sSmartTagstabinthe

AutoCorrectdialogbox.



ThePersistentTaggingGeneratedbySmart

Tags

TounderstandhowSmartTagsworkinOffice,itishelpfulto

haveaconceptualmodelinyourmind.Otherwise,someofthe

behavioryouwillseewhenworkingwithSmartTagswillbe

confusing.

ASmartTaghasarecognitionenginethatispassedtextinthe

documentorworkbook.IftheSmartTagrecognizesasegment

oftext,itcantellWordorExceltotagthetextasbeing

recognized.Thistaggingisstoredandsavedinthedocument



byWordorExcel.Whentextistagged,itremainstaggeduntil

theuserremovesthetagbychoosingRemoveThisSmartTag

fromtheSmartTagmenu.SoevenifaSmartTaghasstopped

recognizingaparticulartermorisnolongeractive,thetagging

inthedocumentcanremain.

TextthathasbeentaggedbyaSmartTaghasitstaggedstate

savedintothedocument.Youcanseethistaggingwhenyou

saveintoWordMLformat.Adocumentwiththestocksymbol

MSFThasbeenrecognizedinaWorddocumentbyaSmartTag

withSmartTagtypenamecustomsmarttag.Also,thistagcan

optionallystorecustompropertiesinthedocumentwhenit

recognizesaterm.Inthisexample,theSmartTagstoresthe

propertiesLongStockNameandthecurrentStockValue.Youcanseeall

thisintheWordMLmarkup:


w:st="on">MSFT



CreatingDocument-LevelSmartTagswithVSTO

ThesimplestwaytocreateaSmartTagistousethesupportin

VisualStudio2005ToolsforOffice(VSTO)fordocument-level

SmartTags.VSTOprovidessomeclassesthatenableyouto

createaSmartTageasily.First,VSTOprovidesaclasscalled

SmartTagintheMicrosoft.Office.Tools.Wordnamespaceandthe

Microsoft.Office.Tools.Excelnamespace.Youcreateaninstance

ofthisSmartTagclasstodefineanewSmartTag.The

constructoroftheSmartTagobjecttakestwoparameters:a

uniqueidentifierandthecaptionthatwilldisplayintheSmart

Tagmenu.Theuniqueidentifierisconstructedusinga

namespaceURIsuchas"http://vsto.aw.com"andatagtypename

suchas"mytagtypename"separatedbyanumbersign,resultingin

"http://vsto.aw.com#mytagtypename".

TheSmartTagobjecthasseveralimportantpropertiesand

methods.TheSmartTagobject'sTermspropertyreturnsa

StringCollectiontowhichyoucanaddwordsyouwantto

recognize.TheSmartTagobject'sActionspropertymustbeset

toanarrayofActionobjectsrepresentingtheactions(themenu

items)youwantdisplayedforyourSmartTag.VSTOprovidesa

classcalledActionintheMicrosoft.Office.Tools.Wordnamespace

andtheMicrosoft.Office.Tools.Excelnamespacethatyoucan

instantiate.TheconstructoroftheActionobjecttakesone

parameter:thecaptionthatwilldisplayintheSmartTagmenu

fortheaction.AfteryouhavecreatedanActionobjectforeach

actionyouwanttomakeavailableforyourSmartTag,youcan

settheSmartTag.Actionspropertytoanarraycontainingallthe

Actionobjectsyouwanttoprovide.Finally,youcanhandlethe

Action.ClickeventforeachActiontobecalledbackbyWordor

ExcelwhentheuserselectsthatactionfromtheSmartTag

menu.

AfteryouhavecreatedaSmartTagobject,setthe

SmartTag.Termscollection,createdoneormoreActionobjects,



andsetSmartTag.Actions,youmustremembertoaddthe

newlycreatedSmartTagtotheVstoSmartTagscollectiononthe

VSTODocumentobjectforWordandontheVSTOWorkbook

objectforExcel.

Listing16.1showsasimpleWordVSTOcustomizationthat

illustratesthesesteps.First,itcreatesaSmartTaginstance

passing"http://vsto.aw.com#fish"astheidentifierand"Fish

Catcher"asthecaption.Thenitaddstwotermstorecognize

usingSmartTag.Terms:"Mackerel"and"Halibut".Notethataterm

cannotcontainaspace.Atermsuchas"EricCarter"couldnot

beaddedtothetermscollection,forexample.

Twoactionsarecreated:onewiththecaption"&Fishing///&Catcha

fish"andtheotherwiththecaption"&Fishing///&Throwitback".

Theampersand(&)inthesestringsindicateswhichlettertouse

asanacceleratorforthemenu.Theuseofthethreeforward

slashestellsWordtocreateamenucalledFishingwithachild

menucalledCatchafishandasecondchildmenucalledThrow

itback.TheseactionsareaddedtotheSmartTag.Actions

propertybycreatinganewarrayofActionscontainingboth

actions.Clickeventsraisedbythetwoactionsarehandledby

thecode.Finally,theSmartTaginstancethatwascreatedis

addedtotheVstoSmartTagscollectionassociatedwiththe

documentobject.



Listing16.1.AVSTOWordCustomizationThat

AddsaSmartTag



ImportsMicrosoft.Office.Tools.Word

PublicClassThisDocument

PrivateSubThisDocument_Startup(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMe.Startup

DimmySmartTagAsNewSmartTag(_

"http://vsto.aw.com#fish","FishCatcher")



mySmartTag.Terms.Add("Mackerel")

mySmartTag.Terms.Add("Halibut")

DimmyActionAsNewAction("&Fishing///&Catchafish...")

DimmyAction2AsNewAction("&Fishing///&Throwitback...")

mySmartTag.Actions=NewAction(){myAction,myAction2}

AddHandlermyAction.Click,AddressOfmyAction_Click

AddHandlermyAction2.Click,AddressOfmyAction2_Click

Me.VstoSmartTags.Add(mySmartTag)

EndSub

PrivateSubmyAction_Click(ByValsenderAsObject,_

ByValeAsActionEventArgs)

MsgBox(String.Format(_

"Youcaughtafishatposition{0}.",_

e.Range.Start))

EndSub

PrivateSubmyAction2_Click(ByValsenderAsObject,_

ByValeAsActionEventArgs)

MsgBox(String.Format(_

"Youthrewbackafishatposition{0}.",_

e.Range.Start))

EndSub

EndClass



ThecodetoaddaSmartTaginExcelisverysimilarandis

showninListing16.2.Themainchangesaretousethe

SmartTagandActionclassesfromthe

Microsoft.Office.Tools.Excelnamespaceandtousethe

VstoSmartTagscollectionofftheWorkbookobject.Becausethe

codeinListing16.2iswritteninSheet1,theWorkbookobjectis

accessedusingGlobals.ThisWorkbook.



Listing16.2.AVSTOExcelCustomizationThat

AddsaSmartTag



ImportsMicrosoft.Office.Tools.Excel

PublicClassSheet1



PrivateSubSheet1_Startup(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMe.Startup

DimmySmartTagAsNewSmartTag(_

"http://vsto.aw.com#fish","FishCatcher")

mySmartTag.Terms.Add("Mackerel")

mySmartTag.Terms.Add("Halibut")

DimmyActionAsNewAction("&Fishing///&Catchafish...")

DimmyAction2AsNewAction("&Fishing///&Throwitback...")

mySmartTag.Actions=NewAction(){myAction,myAction2}

AddHandlermyAction.Click,AddressOfmyAction_Click

AddHandlermyAction2.Click,AddressOfmyAction2_Click

Globals.ThisWorkbook.VstoSmartTags.Add(mySmartTag)

EndSub

PrivateSubmyAction_Click(ByValsenderAsObject,_

ByValeAsActionEventArgs)

MsgBox(String.Format("Youcaughtafishatposition{0}.",_

e.Range.Address(_

ReferenceStyle:=Excel.XlReferenceStyle.xlA1))

EndSub

PrivateSubmyAction2_Click(ByValsenderAsObject,_

ByValeAsActionEventArgs)

MsgBox(String.Format(_

"Youthrewbackafishatposition{0}.",_

e.Range.Address(_

ReferenceStyle:=Excel.XlReferenceStyle.xlA1)))

EndSub

EndClass



ActionEvents

InListing16.1andListing16.2,wehandledtheclickeventof

theActionobject.Thecodethathandledtheclickeventused

theActionEventArgsargumenteandaccessedthe

ActionEventArgs.RangepropertytogetaWord.Rangeobject

forWordandanExcel.RangeobjectforExcel.TheRange



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

Chapter 16. Working with Smart Tags in VSTO

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

×