Understanding the Word object model from the view ofnetWord文档下载推荐.docx
《Understanding the Word object model from the view ofnetWord文档下载推荐.docx》由会员分享,可在线阅读,更多相关《Understanding the Word object model from the view ofnetWord文档下载推荐.docx(3页珍藏版)》请在冰豆网上搜索。
ASPJS
PHP工程
ASP.NET
网站建设UML
J2EESUN
.NET
VCVBVFP
网络维护
数据库DB2
SQL2000
Oracle
Mysql
服务器
Win2000
OfficeC
DreamWeaver
FireWorks
Flash
PhotoShop
上网宝典
CorelDraw
协议大全
网络安全
微软认证
硬件维护
CPU
主板
硬盘
内存
显卡
显示器
键盘鼠标
声卡音箱
打印机
机箱电源
BIOS
网卡
C#
Java
Delphi
2005
当前位置:
>
程序开发>
编程语言>
.NET>
临时文章
UnderstandingtheWordObjectModelfroma.NETDeveloper'
sPerspective
作者:
未知时间:
2004-10-2712:
12出处:
Blog责编:
chinaitpower
摘要:
暂无
Summary:
ProvidesinformationonhowtouseMicrosoftVisualStudioToolsfortheMicrosoftOfficeSystemtotakeadvantageoftheobjectsavailableinMicrosoftOfficeWord2003.ItintroducesseveralimportantWordobjectsandprovidesexamplesofhowtousethem.YouwilllearnhowtoworkwithWord2003applicationsanddocuments,aswellaswithsomeofthemoreimportantpropertiesandmethods.(105printedpages)
DownloadtheWordObject.exefromtheMicrosoftDownloadCenter.
Contents
Introduction
GettingStartedwithaWordProject
TheUnderpinnings:
DocumentsandTemplates
Bird'
s-EyeViewoftheWordObjectModel
TheApplicationObject
TheDocumentObject
TheSelectionObject
TheRangeObject
TheBookmarkObject
SearchingandReplacingText
Printing
CreatingWordTables
Summary
Microsoft®
Wordisprobablyoneofthemostcommonlyusedsoftwareproductsintheworldtoday.MostpeopleusingWordgetbyjustfinewithoutwritinganycodeatall,althoughWordhasarichandpowerfulobjectmodelmakingiteminentlyprogrammable.MicrosoftVisualStudioToolsfortheMicrosoftOfficeSystemenablesdeveloperstointeractwiththeobjectsprovidedbytheMicrosoftOfficeWord2003objectmodelbyusinga.NETlanguage,suchasMicrosoftVisualBasic®
.NETorMicrosoftVisualC#®
.Wordpossessesarichfeatureset,allofwhichareaccessiblethroughcode.Therearequiteafewobjectstolearnabout,whichcanbeconfusingwhenyou'
refirstgettingstarted.Conveniently,Wordobjectsarearrangedinahierarchicalfashion,andyoucangetagoodstartontheobjectmodelbyfocusingonthetwomainclassesatthetopofthehierarchy,theApplicationandDocumentclasses.Focusonthesetwoclassesmakessensewhenyouconsiderthatmostofthetimeyou'
lleitherbeworkingwiththeWordapplicationitself,ormanipulatingWorddocumentsinsomeway.
AsyoudigintotheWordobjectmodel,you'
llfindthatitemulatestheWorduserinterface,makingiteasytoguessthattheApplicationobjectprovidesawrapperaroundtheentireapplication,eachDocumentobjectrepresentsasingleWorddocument,theParagraphobjectcorrespondstoasingleparagraph,andsoforth.Eachoftheseobjectshasmanymethodsandpropertiesthatallowyoutomanipulateandinteractwithit.ThebehaviorsofthemembersoftheseobjectsaregenerallyeasytoguessÃ
‚Â
—howaboutthePrintOutmethod?
Otherscanbemoreobscureandsometimestrickytousecorrectly.Onceyoulearnthebasics,you'
llfindthatthereisn'
tanythingyoucandointheWorduserinterfacethatyoucan'
tdojustaseasilyincode.ProgramminginWordallowsyoutoautomaterepetitivetasks,andtoextendandcustomizethefunctionalitybuiltintoWord.
Inthisdocument,you'
lllearnhowtotakeadvantageofmanyoftheobjectsinWord2003,andyouwillalsobeintroducedtosomeoftheproperties,methods,andeventsofeachobject.You'
lllearnhowtoworkwithWordapplicationsanddocuments,aswellaswithsomeoftheirmoreimportantmethodsandproperties.
Note
ProgrammingWordanditsobjectsfromVisualBasic.NETfeelsmuchlikeprogramminginVBA.VisualBasic.NEThandlesoptionalparameters,andallowslatebinding,justlikeVBA.C#,ontheotherhand,providesuniquechallengeswhenprogrammingagainsttheWordobjectmodel.BecauseC#doesn'
tsupportoptionalparameters,parameterizedproperties,orlatebinding,you'
llneedtohandlemanyoftheWordmethodsandpropertiesspeciallywhenprogramminginC#.ThisdocumentpointsoutthedifferencesbetweenVisualBasic.NETandC#programming,astheycomeup.
WhenyoucreateanewOfficeprojectinVisualStudio.NET,youaregiventheoptionofcreatinganewWordDocumentorWordTemplateproject,asshowninFigure1.
Figure1.YoucancreateeitheraWordDocumentoraWordTemplateprojectinVisualStudio.NET.
VisualStudio.NETautomaticallycreatesacodefilenamedThisDocument.vborThisDocument.csinyournewWordprojectforbothDocumentandTemplateprojects.OpenThisDocumentinyournewproject.You'
llseethatapublicclassnamedOfficeCodeBehindhasalreadybeengeneratedforyou.ExpandthehiddenGeneratedinitializationcoderegion.TheOfficeCodeBehindclassincludescodethatwrapstheWord.DocumentandWord.Applicationobjects:
'
VisualBasic
FriendWithEventsThisDocumentAsWord.Document
FriendWithEventsThisApplicationAsWord.Application
//C#
privateWord.ApplicationthisApplication=null;
privateWord.DocumentthisDocument=null;
Thesetwovariablesaredeclaredforyou:
∙ThisDocument:
RepresentstheWordDocumentobject,andallowsaccesstoallofthebuilt-inDocumentmembersinWord,includingmethods,propertiesandevents.
∙ThisApplication:
RepresentstheWordApplicationobject,andallowsaccesstoalloftheApplicationobject'
smembers,includingevents.
TheavailabilityofthesetwopredefinedvariablesallowseasyaccesstobothWordobjectsinyourcodewithouthavingtodeclareseparateWord.DocumentorWord.ApplicationobjectsÃ
—justuseThisDocumentandThisApplication.
EachofthefollowingsectionsdigsintotheDocumentandApplicationobjects,pickingspecificmembersofeachobjectfordemonstration.Wordhasaveryrichobjectmodel,anditwouldbeimpossibletodigintoallofthemembershere:
You'
llgetenoughoftheflavoroftheobjectmodeltobeabletogetstarted,andyou'
lllearnenoughtousetheWordonlinehelpformoredetails.
Tip
Throughoutthisarticle,you'
llseemanyusesoftheCTypeandDirectCastmethodsintheVisualBasic.NETcode.ThereasonforthisisthatthesampleprojecthasitsOptionStrictsettingon—thismeansthatVisualBasic.NETrequiresstricttypeconversions.ManyWordmethodsandpropertiesreturnObjecttypes:
Forexample,the_StartupprocedureispassedvariablesnamedapplicationanddocumentasObjecttypes,andtheCTypefunctionisusedtoexplicitlyconverteachtoWord.ApplicationandWord.Documentobjects,respectively.Therefore,tobeasrigorousaboutconversionsaspossible,thesamplehasenabledOptionStrict,andhandleseachtypeconversionexplicitly.Ifyou'
reaC#developerreadingthisdocument,you'
lllikelyappreciatethisdecision.However,asyou'
llseelateron,therearecertainWordfeaturesthatdon'
ttranslatewellintotheobject-orientedparadigmÃ
—itcansometimesbemoreconvenienttoworkwithOptionStrictoff.Forthemostpart,you'
llwanttoworkwithOptionStricton;
you'
lllearnaboutthefewexceptionsastheyarise.
BeforeyoucaneffectivelyprogramWord,youneedtounderstandhowWordworks.Mostoftheactionsyou'
llperformincodehaveequivalentsintheuserinterfaceonthemenusandtoolbars.ThereisalsoanunderlyingarchitecturethatprovidesstructuretothoseUIchoices.Oneofthemostimportantconceptsistheideaoftemplates.YouprobablyarealreadyfamiliarwiththeconceptofatemplateÃ
—aWordtemplatecancontainboilerplatetextandstylesaswellascode,toolbars,keyboardshortcutsandAutoTextentries.WheneveryoucreateanewWorddocument,itisbasedonatemplate,whichisdistinguishedbythe.dotfilenameextensionÃ
—Worddocumentshavea.docfilenameextension.Thenewdocumentislinkedtothetemplate,andhasaccesstoalltemplateitems.Ifyoudonotspecifyacustomtemplate,anynewdocumentsyoucreatewillbebasedontheNormal.dotdefaulttemplate,whichisinstalledwhenyouinstallWord.
AboutNormal.dot
TheNormal.dottemplateisglobalinscope,andisavailabletoeverydocumentyoucreate.Youcould,ifyouwantedto,putallofyourcodeintheNormal.dotandbaseallofthedocumentsinyourenvironmentonyourNormaltemplate.Butthefilecouldbecomequitelarge,soformanydevelopers,abettersolutionistocreatecustomizedtemplatesforspecificapplications.DocumentscreatedusingyourcustomtemplatestillhaveaccesstothecodeinthedefaultNormaltemplate.Infact,youcanattachadocumenttomorethanonecustomtemplateinadditiontoNormalifyousodesire.
TemplatesandYourCode
Youarenotlimitedtotemplatesascontainersforstylesandcode;
youcanalsocustomizeandwritecodeinindividualdocumentswithoutaffectingthecontentofthetemplatethedocumentisbasedon.WhenWordrunsyourcode,itusesthefullyqualifiedreferenceofthesource(whichcanbeatemplateorthedocument),themodulename,andtheprocedurename.Thisoperatesinasimilarfashiontonamespaces,keepingproceduresseparated.Figure2showstheCustomizedialogboxfortoolbars,illustratingthisconcept.Eachprocedureisfullyqualifiedwiththenameoftheproject,themodule,andtheprocedurename.Inthiscase,theitemselectedintherightpanereferstoaprocedurenamedTileVerticalthatiscontainedintheTilemoduleinNormal.dot.TheSaveDocumentprocedurelistedimmediatelybelowitiscontainedintheactivedo