Upload
marshall-parker
View
215
Download
0
Tags:
Embed Size (px)
Citation preview
Building COM Add-InsBuilding COM Add-Ins
Don KielyDon KielySoftware TechnologistSoftware TechnologistThird Sector TechnologiesThird Sector TechnologiesFairbanks, AlaskaFairbanks, Alaska
4-4024-402
Me.AboutMe.About
Software Technologist for Third Sector Software Technologist for Third Sector Technologies in Fairbanks, AlaskaTechnologies in Fairbanks, Alaska
Develop software and Web applicationsDevelop software and Web applications www.infoinsights.comwww.infoinsights.com www.thethirdsector.comwww.thethirdsector.com
Business and technology consultingBusiness and technology consulting
My Other JobsMy Other Jobs
AuthorAuthor Several books, including Several books, including VB Programmer’s VB Programmer’s
Guide to the Windows RegistryGuide to the Windows Registry Regular contributor to several Regular contributor to several
publications, including Informant’s publications, including Informant’s Microsoft Office & VBA Developer, VBPJ, Microsoft Office & VBA Developer, VBPJ, and Information Weekand Information Week
TrainingTraining VB, VBA, VI, and SQL Server instructor for VB, VBA, VI, and SQL Server instructor for
Application Developers Training CompanyApplication Developers Training Company
What Is A COM Add-in?What Is A COM Add-in?
ActiveX DLL or EXE with special ActiveX DLL or EXE with special registrationregistration
Standard way of extending Office 2000Standard way of extending Office 2000 Across all host applicationsAcross all host applications Available both in user interface and Available both in user interface and
Visual Basic for Applications environmentVisual Basic for Applications environment Still need to deal with various object Still need to deal with various object
modelsmodels Create with any COM development toolCreate with any COM development tool
In the Past, Add-ins…In the Past, Add-ins…
Had different models across OfficeHad different models across Office Usually had a pre-defined file Usually had a pre-defined file
extensionextension Document-centricDocument-centric
Had to be in a certain disk directory Had to be in a certain disk directory to appear in the Add-ins menuto appear in the Add-ins menu Or had to be listed in a special .INI fileOr had to be listed in a special .INI file
But now, the registry provides a common But now, the registry provides a common mechanism to discover installed add-ins.mechanism to discover installed add-ins.
Why Bother?Why Bother?
Share code among multiple Office Share code among multiple Office applicationsapplications Without the mess of Office 97 add-insWithout the mess of Office 97 add-ins Maybe for uniform user interface toolsMaybe for uniform user interface tools
Protect intellectual propertyProtect intellectual property Increased performanceIncreased performance It’s coolIt’s cool
Separates the developers from the Separates the developers from the mere power usersmere power users
Add-Ins In The RegistryAdd-Ins In The Registry
HKEY_CURRENT_USERHKEY_CURRENT_USER \Software \Software \Microsoft\Office \Microsoft\Office \<application name> \<application name> \AddIns \AddIns
SettingsSettings ProgID: WordDocMgt.ConnectProgID: WordDocMgt.Connect FriendlyName: WordDocMgtFriendlyName: WordDocMgt LoadBehaviorLoadBehavior Sometimes others. . . Sometimes others. . .
End-User InterfaceEnd-User Interface
Add COM Add-Ins…menu itemAdd COM Add-Ins…menu item Old Tools|Add-ins… still supportedOld Tools|Add-ins… still supported
LoadBehavior governs instantiationLoadBehavior governs instantiation 0: Not loaded0: Not loaded 2: Loaded at startup2: Loaded at startup 4: Load when run from command line 4: Load when run from command line
(VB only)(VB only) 8: Load on demand8: Load on demand 16: Load on next startup (Office only)16: Load on next startup (Office only)
Then changes LoadBehavior to 8Then changes LoadBehavior to 8
Add-In EventsAdd-In Events OnConnection when added to hostOnConnection when added to host
User adds or host starts upUser adds or host starts up Code to integrate add-in with hostCode to integrate add-in with host
OnStartupComplete when host finished loadingOnStartupComplete when host finished loading OnAddinstUpdate when any add-in added or removed OnAddinstUpdate when any add-in added or removed
in hostin host OnBeginShutDown when host begins shutdownOnBeginShutDown when host begins shutdown OnDisconnection when removed from hostOnDisconnection when removed from host
User removes manually or host shutting downUser removes manually or host shutting down Undo OnConnection workUndo OnConnection work
Plus, designer is a class module, so Initialize and Plus, designer is a class module, so Initialize and Terminate eventsTerminate events
Office Add-Ins ObjectsOffice Add-Ins Objects
Application objectApplication object COMAddIns collectionCOMAddIns collection COMAddIn objectCOMAddIn object
Warning: AddIns collection for Warning: AddIns collection for backward compatibilitybackward compatibility
Building Add-In ObjectsBuilding Add-In Objects
Build with MOD or Visual BasicBuild with MOD or Visual Basic More flexibility with Visual BasicMore flexibility with Visual Basic
DLL or EXEDLL or EXE Property pages for host applicationProperty pages for host application Run standaloneRun standalone
ActiveXActiveX®® designer designer Optional, but convenientOptional, but convenient Manages registry settings for youManages registry settings for you Include one for each hostInclude one for each host
Connect object used to load add-inConnect object used to load add-in Templates in MOD for VB, VC++, VJ++Templates in MOD for VB, VC++, VJ++
Can’t use VB’s add-in project code for OfficeCan’t use VB’s add-in project code for Office
Steps In VBASteps In VBA
Develop in any host applicationDevelop in any host application Create a new Visual Basic for Applications Create a new Visual Basic for Applications
Add-in projectAdd-in project Add reference to Office object models Add reference to Office object models
you’ll useyou’ll use Fill in designer propertiesFill in designer properties Export designerExport designer Import for each host application you’ll supportImport for each host application you’ll support
Change name, hostChange name, host Write event codeWrite event code
OnConnection ParametersOnConnection Parameters
ApplicationApplication ConnectModeConnectMode
ext_cm_Startupext_cm_Startup ext_cm_AfterStartupext_cm_AfterStartup ext_cm_Externalext_cm_External ext_cm_CommandLineext_cm_CommandLine
AddInInstAddInInst custom() As Variantcustom() As Variant
1: how the host was started: standalone, 1: how the host was started: standalone, embedded document, via automationembedded document, via automation
2+: depends on host2+: depends on host
OnDisConnection parametersOnDisConnection parameters
RemoveModeRemoveMode ext_dm_UserClosedext_dm_UserClosed
Clean up host app’s user interfaceClean up host app’s user interface ext_dm_HostShutdownext_dm_HostShutdown
custom() As Variantcustom() As Variant
A Few DetailsA Few Details
Put code specific to a host application in Put code specific to a host application in Designer; shared code in code or class Designer; shared code in code or class modulemodule Must use class to trap WithEventsMust use class to trap WithEvents
Package and Deployment WizardPackage and Deployment Wizard Properly registers add-ins for each hostProperly registers add-ins for each host Ignores the Install Location you setIgnores the Install Location you set
Default becomes \Program Files\[add-in]Default becomes \Program Files\[add-in]
If Load on Demand, disconnecting If Load on Demand, disconnecting counts as a ‘demand’counts as a ‘demand’ OnConnection, AddinsUpdate, OnConnection, AddinsUpdate,
OnDisconnection will fireOnDisconnection will fire
Steps In Visual BasicSteps In Visual Basic
With or without designer?With or without designer? Create new ActiveX DLL projectCreate new ActiveX DLL project
Set reference to Microsoft Add-in DesignerSet reference to Microsoft Add-in Designer-- or ---- or --
Create new add-in projectCreate new add-in project Sets reference to extensibility object librarySets reference to extensibility object library
Still need the VBA versionStill need the VBA version Consider using template projectConsider using template project
Add reference to Office object models you’ll Add reference to Office object models you’ll useuse Not necessarily host application’s object libraryNot necessarily host application’s object library
Write event codeWrite event code
VB Application DesignVB Application DesignWithout DesignerWithout Designer Implement IDTExtensibility2 in a Connect Implement IDTExtensibility2 in a Connect
class moduleclass module With only one host, can early bind the With only one host, can early bind the
application object in OnConnectionapplication object in OnConnection How use add-in in multiple hosts?How use add-in in multiple hosts?
Declare as Object: late boundDeclare as Object: late bound Create Connect class for each hostCreate Connect class for each host
ConnectWord, ConnectExcel, etc.ConnectWord, ConnectExcel, etc. Single Connect, use TypeOf to test for type of Single Connect, use TypeOf to test for type of
Application object, and Not Is NothingApplication object, and Not Is Nothing Then manually add registry entriesThen manually add registry entries
Register.vbpRegister.vbp No free lunchNo free lunch
VB Application DesignVB Application DesignWith DesignerWith Designer Add one designer for each host appAdd one designer for each host app Need to remove or modify most of the Need to remove or modify most of the
default codedefault code It’s VB-specificIt’s VB-specific Set designer’s Public property to TrueSet designer’s Public property to True
Implement AddinInstance instead of Implement AddinInstance instead of IDTExtensibility2IDTExtensibility2 Remove Implements statementRemove Implements statement
Automatically adds registry entriesAutomatically adds registry entries Kind of a free lunchKind of a free lunch
Then What?Then What?
Display a form in OnConnectionDisplay a form in OnConnection Respond to events from host Respond to events from host
environmentenvironment Manipulate the host’s user interfaceManipulate the host’s user interface
Menu items, toolbar, etc.Menu items, toolbar, etc. Does it really need a user interface?Does it really need a user interface?
Whatever makes sense for the appWhatever makes sense for the app
Load ProgrammaticallyLoad Programmatically Application.COMAddins collectionApplication.COMAddins collection
NOT the AddIns collection (if exists)NOT the AddIns collection (if exists) One way:One way:Dim objAddIn As COMAddInDim objAddIn As COMAddInFor Each objCAddIn In Application.COMAddInsFor Each objCAddIn In Application.COMAddIns If objAddIn.Description = "AddInName" ThenIf objAddIn.Description = "AddInName" Then If objAddIn.Connect = False ThenIf objAddIn.Connect = False Then objAddIn.Connect = TrueobjAddIn.Connect = True COMAddIns.UpdateCOMAddIns.Update Exit SubExit Sub End IfEnd If End IfEnd If Debug.Print objAddIn.GUID, objAddIn.ProgIDDebug.Print objAddIn.GUID, objAddIn.ProgIDNextNext
Debugging Your Add-InDebugging Your Add-In
Easiest with ActiveX DesignerEasiest with ActiveX Designer Visual Basic manages registryVisual Basic manages registry
Things get messy when you Things get messy when you stop executionstop execution OnDisconnection doesn’t fireOnDisconnection doesn’t fire Remove using Add-in ManagerRemove using Add-in Manager
Add-ins For VBEAdd-ins For VBE
Uses Microsoft Visual Basic for Uses Microsoft Visual Basic for Applications ExtensibilityApplications Extensibility Different from Visual Basic’s extensibility Different from Visual Basic’s extensibility
librarylibrary But most code can be duplicatedBut most code can be duplicated
VBE ObjectsVBE Objects VBProjectVBProject VBComponentVBComponent VBE (top-level)VBE (top-level)
Questions?Questions?
Thanks for attending!Thanks for attending!
Please remember to fill out the Please remember to fill out the evaluation forms! How can I make this evaluation forms! How can I make this
a better presentation?a better presentation?
Don KielyDon [email protected]@computer.org
Third Sector TechnologiesThird Sector Technologies
Appendix A: IdeasAppendix A: Ideas
The SimpleThe Simple Save all open documents at onceSave all open documents at once Close all open document windowsClose all open document windows Insert MapPoint map in documentInsert MapPoint map in document
The SophisticatedThe Sophisticated Implement logging of user activity Implement logging of user activity
(hook into host application events)(hook into host application events) Modify the application response to Modify the application response to
events and user actionsevents and user actions