[python-win32] launching Word with COM..how to tell when it's closed?

Jeff Shannon jeff@ccvcorp.com
Wed, 10 Apr 2002 13:36:53 -0700


> "David Primmer" <dave@primco.org> wrote:
>
> I'm thinking that since I have a word application object already in
> python I don't have to do all the Class Module stuff that I did within
> Word but this is a guess. However, it does say that I need to " declare
> an object of type Application with events" Is this any different, and if
> so, is there a special way to declare this kind of app object?

Yes, there is a special way.  You first need to create a class that has methods
implementing your event handlers:

class WordEvents:
    def DocumentBeforeClose(self, Doc, Cancel):
        [...]  # perform your checking, etc, here

Then, instead of the usual way to create a COM object in Python, you use a special
version that combines the COM wrapper with your event handler class:

wordobj = win32com.client.DispatchWithEvents('Word.Application', WordEvents)
# replaces  wordobj = win32com.client.Dispatch('Word.Application')

Now, provided that you've given your event handler functions the correct call
signature (as defined by Word), they should be called automatically whenever the
appropriate event happens in Word.  (No need to explicitly register each event
handler.)

If you're doing *any* amount of COM work in Python, and especially if you're scripting
MS Office, I cannot recommend strongly enough the book "Python Programming on Win32",
by Mark Hammond and Andy Robinson (O'Reilly).  It has detailed explanations and
examples, including lots of working code for controlling Excel, and lots of examples
of interacting with Visual Basic.

Jeff Shannon
Technician/Programmer
Credit International