PERfORMINg LATE BINDINg uSINg MARSHAL.gETACTIvEOBjECT()
Sometimes you need to interact with an application that’s already running. In this case, you don’t
want to create a new object; you want to gain access to an existing object. The technique used to
perform this type of late binding is to call
Marshal.GetActiveObject()
with the type of object you
548592c09.indd 189
2/24/10 12:48:24 PM
www.finebook.ir
190
❘
CHAPTER 9
InteractIng wIth cOM Objects
want to access. Typically, you use this technique with application objects, such as a running copy of
Word. Listing 9-5 shows an example of how to use
Marshal.GetActiveObject()
to gain access to
a running Word application.
LISTINg 9-5:
Working with a running copy of Word
# Import only the required classes from System.
from System.Runtime.InteropServices import Marshal
# Obtain a pointer to the running Word application.
# Word must be running or this call will fail.
WordObj = Marshal.GetActiveObject(‘Word.Application’)
# Add a new document to the running copy of Word.
MyDoc = WordObj.Documents.Add()
# Get the Application object.
App = MyDoc.Application
# Type some text in the document.
App.Selection.TypeText(‘Hello World’)
App.Selection.TypeParagraph()
App.Selection.TypeText(‘Goodbye!’)
The
import
statement differs from normal in this example. Notice that you can drill down into
the namespace or class you want, and then import just the class you need. In this case, the example
requires only the
Marshal
class from
System.Runtime.InteropServices
.
The first step is to get the running application. You must have a copy of Word running for
this step to work; otherwise, you get an error. The call to
Marshal.GetActiveObject()
with
Word.Application
returns a Word object,
WordObj
. This object is the same object you get when
working with Visual Basic for Applications (VBA). In fact, if you can do it with VBA, you can do
it with IronPython.
After gaining access to Word, the application adds a new document using
WordObj.Documents.Add()
.
It then creates an
Application
object,
App
. Using the
App.Selection.TypeText()
method, the
application types some text into Word, as shown in Figure 9-16. Of course, you can perform any task
required — the example does something simple for demonstration purposes.
fIguRE 9-16:
You can control Word using IronPython as easily as you can using VBA.
548592c09.indd 190
2/24/10 12:48:24 PM
www.finebook.ir
Do'stlaringiz bilan baham: |