Accessing an Interop Object from a Host Control

Sometimes you may need to access the Interop object associated with a given host control. For example, you might be working with the host controls and want to call a method that specifically requires an Interop object. You can call the InnerObject property of the host control to return its underlying Interop object.

Suppose you are creating a new toolbar and you want to ensure that it is available only when a particular VSTO-enabled document is running and has focus. You can set CustomizationContext to the Document object. CustomizationContext is a function on the Word Application object that tells which document the toolbars, menu bars, and key bindings will be saved in. Because the Application object doesn't know anything about VSTO host items or host controls, it requires that an Interop object be passed to any of its methods; you cannot pass the VSTO object directly.

Listing 6.14 shows how to set CustomizationContext to the Interop document by using InnerObject. If you were to try to set CustomizationContext to the VSTO document (without calling InnerObject), it would raise an InvalidCast exception when you run the solution. To see this in use when creating a button for a toolbar, see the earlier example in Listing 6.3.

Listing 6.14. Using the InnerObject property of a host control

' Set the CustomizationContext property of a Word application ' to the Interop document.

Me.Application.CustomizationContext = Me.InnerObject

' If you do not call the InnerObject property of ' ThisDocument, VSTO raises an InvalidCast exception ' with the following code. Me.Application.CustomizationContext = Me

0 0

Post a comment