Tải bản đầy đủ - 0 (trang)
Chapter 7. Working with Word Events

Chapter 7. Working with Word Events

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

EventsintheWordObjectModel

UnderstandingtheeventsintheWordobjectmodeliscritical,

becausethisisoftentheprimarywaythatyourcodeisrun.

ThischaptercoversalltheeventsintheWordobjectmodel,

whentheyareraised,andthetypeofcodeyoumightassociate

withtheseevents.

SomeoftheeventsintheWordobjectmodelarerepeatedon

theApplicationandDocumentobjects.Thisrepetitionallows

youtodecidewhetheryouwanttohandletheeventforall

documentsorforaparticulardocument.Ifyouwanttoknow

whenanydocumentisclosed,forexample,youwouldhandle

theApplicationobject'sDocumentBeforeCloseevent.Ifyou

wanttoknowwhenaparticulardocumentisclosed,youwould

handletheCloseeventonaparticularDocumentobject.When

aneventisrepeatedontheApplicationandDocumentobject,it

israisedfirstontheDocumentobjectandthenonthe

Applicationobject.



AdvancedTopic:WhyAreThereMultipleApplicationand

DocumentEventInterfaces?

WhenyouworkwiththeWordObjectmodel,youwillquicklynoticemultiple

publicinterfaces,classes,anddelegatesthatcontainthetext"ApplicationEvents"

and"DocumentEvents":

ApplicationEventsInterface

ApplicationEvents_EventInterface

ApplicationEvents_SinkHelperclass

ApplicationEvents2Interface

ApplicationsEvents2_EventInterface

ApplicationEvents2_*Delegates

ApplicationEvents2_SinkHelperclass

ApplicationEvents3Interface

ApplicationsEvents3_EventInterface

ApplicationEvents3_*Delegates

ApplicationEvents3_SinkHelperclass

ApplicationEvents4Interface

ApplicationsEvents4_EventInterface

ApplicationEvents4_*Delegates

ApplicationEvents4_SinkHelperclass

DocumentEventsInterface

DocumentEvents_EventInterface

DocumentEvents_*Delegates

DocumentEvents_SinkHelperclass



DocumentEvents2Interface

DocumentEvents2_EventInterface

DocumentEvents2_*Delegates

DocumentEvents2_SinkHelperclass

Theonlyitemsfromthislistthatyoushouldeveruseinyourcodearetheones

inbold:ApplicationEvents4_Eventinterface,theApplicationEvents4_*delegates,

theDocumentEvents2_Eventinterface,andtheDocumentEvents2_*delegates.

YoushouldusetheApplicationEvents4_Eventinterfaceandthe

DocumentEvents2_Eventinterfaceonlywhenyouhavetocastanobject

declaredasApplicationorDocumenttothecorrespondingeventinterface

becauseamethodnameandeventnamecollide.Anexampleofthisisthe

DocumentobjectthathasbothaClosemethodandaCloseevent.Todistinguish

betweenthetwo,youwillhavetocasttheDocumentobjecttothe

DocumentEvents2_EventinterfacewhenyouwanttohandletheCloseevent.

ThereasonfortheotheritemsinthislistispartiallyexplainedinChapter1,"An

IntroductiontoOfficeProgramming."Thisexplanation,however,coversonlythe

existenceoftheSinkHelperclassandwhytherearebothan

ApplicationEvents/DocumentEventsinterfaceandan

ApplicationEvents_Event/DocumentEvents_Eventinterface.Thereasonwhy

therearemultiplenumberedeventinterfacesgoesbacktotheoriginalCOM

implementationoftheWordobjectmodel.

TheWordApplicationandDocumentCOMobjectsaredefinedbytheIDL

definitionshowninListing7.1.NotethattheApplicationobjecthasfourevent

interfacesandDocumenthastwo.ApplicationEvents4isthedefaultevent

interfaceforWord'sApplicationobject,andDocumentEvents2isthedefault

eventinterfaceforWord'sDocumentobject.ApplicationEvents,

ApplicationEvents2,ApplicationEvents3,andDocumentEventsaresupportedfor

legacypurposes.WordhadtokeeptheseolderinterfacesinplaceforbackwardcompatibilityreasonsbecauseolderversionsofWordusedtheseinterfaces.



Listing7.1.TheIDLDefinitionofWord'sApplicationand

DocumentObjects



[

uuid(000209FF-0000-0000-C000-000000000046),

]

coclassApplication{

[default]interface_Application;

[source]dispinterfaceApplicationEvents;

[source]dispinterfaceApplicationEvents2;

[source]dispinterfaceApplicationEvents3;

[default,source]dispinterfaceApplicationEvents4;

};

[



uuid(00020906-0000-0000-C000-000000000046),

]

coclassDocument{

[default]interface_Document;

[source]dispinterfaceDocumentEvents;

[default,source]dispinterfaceDocumentEvents2;

};



VisualStudioGenerationofEventHandlers

Asyouconsidersomeofthecodeinthischapter,youmight

wonderhowyouwilleverrememberthesyntaxofcomplicated

linesofcodesuchasthisone:

PrivateSubApp_DocumentBeforeClose(_

ByValdocumentAsWord.Document,_

ByRefcancelAsBoolean)_

Handlesapp.DocumentBeforeClose



Fortunately,VisualStudio2005helpsbygeneratingthiscode

foryou.Whenyouhavedeclaredtheappmembervariableas

havingeventsbyusingtheWithEventskeyword,VisualStudio

displaystheappvariableintheleftdrop-downlistofthecode

editor.Selectappfromtheleftdrop-downlist;thenselectthe

eventthatisraisedbyappthatyouwanttohandlefromthe

rightdrop-downlistinthiscase,DocumentBeforeClose(see

Figure7.1).Whenyouselecttheeventyouwanttohandle,

VisualStudiogeneratestheeventhandlermethod

automatically.



Figure7.1.VisualStudiogenerateseventhandler

codeforyouifyouusetheleftandrightdropdownlistsinthecodeeditor.



[Viewfullsizeimage]



IfyouareusingVSTO,youcanalsousethePropertieswindow

toaddeventhandlerstoyourdocumentclass.Double-clickthe

projectitemforyourdocumentclass.MakesuretheProperties

windowisvisible;ifitisnot,choosePropertiesWindowfrom

theViewmenu.Makesurethatthedocumentclass(typically

calledThisDocument)isselectedinthecomboboxatthetopof

thePropertieswindow.Thenclickthelightning-bolticonto

showeventsassociatedwiththedocument.Typethenameof

themethodyouwanttouseasaneventhandlerintheeditbox

totherightoftheeventyouwanttohandle.

Figure7.2.showsthePropertieswindowandaneventhandler

wehaveaddedbytypingthetextThisDocument_Newinthe

editboxnexttotheNewevent.ThiswillcausetheNewevent

tobehandledbyamethodcalledThisDocument_Newinthe



documentclass.Ifthemethoddoesnotalreadyexist,Visual

Studiowilladdthemethodforyou.



Figure7.2.Addingadocumenteventhandler

usingthePropertieswindowinVSTO.



StartupandShutdownEvents



Severaleventsareraisedwhentheapplicationisstartedand

shutdown.TheWordApplicationobjecthasaStartupevent

thatisraisedwhentheapplicationstartsandbeforeany

documentsareloaded.Thiseventismarkedas"restricted"in

theCOMobjectmodel,however,andprobablyshouldnotbe

used.Theonlykindofcustomizationthatcanhandlethisevent

isanadd-in.Theeventisraisedbeforedocumentsareloaded

andbeforeanautomationexecutablecanestablishanevent

handler.Evenadd-insdonotneedtousethiseventbecause

theyalreadyimplementOnConnection,whichservesthesame

purpose.Ourrecommendationisthatyounotusethe

Applicationobject'sStartupevent.

ForVSTOcustomizations,werecommendthatyouusethe

StartupandShutdowneventsraisedbyVSTOonadocument

projectitem.Startupisraisedwhenthedocumentisopenedor

createdfromatemplate.Shutdownisraisedwhenthe

documentisclosed.Intheprojectitemcreatedforyouby

VSTO,theseeventsarealreadyconnectedforyou,asshownin

Listing7.2.



Listing7.2.AVSTOCustomizationThatHandles

theStartupandShutdownEvents



PublicClassThisDocument

PrivateSubThisDocument_Startup(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMe.Startup

EndSub

PrivateSubThisDocument_Shutdown(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMe.Shutdown

EndSub

EndClass



WordraisestheQuiteventwhentheapplicationshutsdown.

Listing7.3showsanexampleofhandlingtheQuitevent.



Note

Quitisthenameofbothamethodandaneventon

Word'sApplicationobject.Becauseofthiscollision,

youwillhavetousetheCTypeoperatortocastthe

ApplicationobjecttotheApplicationEvents4_Event

interfacewhenaddinganeventhandlerdynamically

usingtheAddHandlerstatement.Ifyouareaddingan

eventhandlerdeclarativelyusingWithEventsand

HandlesasinListing7.3,youdonothavetoworry

aboutthisissue.



Listing7.3.AVSTOCustomizationThatHandles

theQuitEvent



PublicClassThisDocument

PrivateWithEventsappAsWord.Application

PrivateSubThisDocument_Startup(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMe.Startup

app=Me.Application

EndSub

PrivateSubApp_Quit()Handlesapp.Quit

MsgBox("QuitEventRaised")

EndSub

EndClass



NewandOpenDocumentEvents

WordraisesaNewDocumenteventontheApplicationobject

andaNeweventonaDocumentobjectwhenanewdocument

iscreatedbytheusereitherasablankdocumentorfroma

templateorexistingdocument.Theseeventsareneverraised

onsubsequentopensofthedocument.Wordalsoraisesa

DocumentOpeneventontheApplicationobjectandanOpen

eventonaDocumentobjectwhenanexistingdocumentis

opened:

Application.NewDocumentisraisedwhenevera

documentiscreated.WordpassestheDocumentthatwas

createdasaparametertothisevent.

Document.Newisraisedonatemplateoranewblank

document.So,forexample,whenadocumentiscreated

fromatemplate,youcanhandletheNeweventtosetup

thedocumentforthefirsttime.Forsubsequentopensof

thedocument,youcanhandletheOpeneventorthe

StartupeventraisedbyVSTO.

Application.DocumentOpenisraisedwheneveran

existingdocumentisopened.WordpassestheDocument

thatwasopenedasaparametertothisevent.

Document.Openisraisedonanexistingdocumentwhenit

isopened.

Listing7.4showsaVSTOcustomizationthathandlesthe

Applicationobject'sNewDocumenteventandputsintothe

footerofeverynewdocumentcreatedinWordthedatethe

documentwascreatedandthenameoftheuserwhocreated

thedocument.ItalsohandlestheApplicationobject's

DocumentOpeneventtoputintotheheaderofanexisting



documentthatisopenedthedatethedocumentwasopened

andthenameoftheuserwhoopenedthedocument.



Listing7.4.AVSTOCustomizationThatHandles

theApplicationObject'sNewDocumentand

DocumentOpenEvents



PublicClassThisDocument

PrivateWithEventsappAsWord.Application

PrivateSubThisDocument_Startup(ByValsenderAsObject,_

ByValeAsSystem.EventArgs)HandlesMe.Startup

app=Me.Application

EndSub

PrivateSubApp_NewDocument(ByValdocumentAsWord.Document)_

Handlesapp.NewDocument

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

document.Name))

Dimrange1AsWord.Range=document.Sections(1).Footers(_

Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range

range1.Text=String.Format("Createdon{0}by{1}.",_

System.DateTime.Now,app.UserName)

EndSub

PrivateSubApp_DocumentOpen(ByValdocumentAsWord.Document)_

Handlesapp.DocumentOpen

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

document.Name))

Dimrange2AsWord.Range=document.Sections(1).Headers(_

Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range

range2.Text=String.Format("Lastopenedon{0}by{1}.",_

System.DateTime.Now,app.UserName)

EndSub

EndClass



Listing7.5showsVSTOcodebehindatemplatethathandles

theDocumentobject'sNeweventtodisplaythetimeinthe

footerwhenthedocumentiscreatedfromatemplate.Italso

handlestheDocumentobject'sOpeneventtoputintothe

headerthedateanduserwholastopenedthedocumenteach

timethedocumentisopened.

Tounderstandthislisting,itisimportanttounderstandhow

WordtemplatesworkinVSTO.Youshouldwritehandlersforthe

Documentobject'sNeweventonlyinatemplateproject.When

ausercreatesanewdocumentfromthattemplate,thecode

associatedwiththetemplatewillbeassociatedwiththenewly

createddocument,andtheNeweventwillberaisedonthe

newlycreateddocument.

AlsonotethatbecausetheNeweventconflictswiththeNew

keywordinVisualBasic,theHandlesclauseputstheNewevent

insquarebracketssothecompilerknowsthatNewisbeing

usedasaneventnameratherthanakeyword.



Listing7.5.AVSTOCustomizationThatHandles

theDocumentObject'sNewandOpenEvents



PublicClassThisDocument

PrivateSubThisDocument_New()HandlesMe.[New]

MsgBox("Newevent")

Dimrange1AsWord.Range=Me.Sections(1).Footers(_

Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range

range1.Text=String.Format("Createdon{0}by{1}.",_

System.DateTime.Now,Me.Application.UserName)

EndSub

PrivateSubThisDocument_Open()HandlesMe.Open

MsgBox("Openevent")

Dimrange2AsWord.Range=Me.Sections(1).Headers(_

Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range

range2.Text=String.Format("Openedon{0}by{1}.",_

System.DateTime.Now,Me.Application.UserName)

EndSub



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

Chapter 7. Working with Word Events

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

×
x