Capturing COM object events

Alex Martelli aleaxit at yahoo.com
Mon May 28 11:36:49 EDT 2001


"Rush" <rusha at data-tech.com> wrote in message
news:9c4a6c75.0105280514.7c1a4c59 at posting.google.com...
> Newbie here,
> I'm using PythonWin to instantiate an instance of an ActiveX DLL. It
> works GREAT!! Very simple and straightforward.  I can create an
> instance of the object, set its Properties, and invoke its Methods.

So far so good.


> Now, this COM object also returns events, and I have no clue as to how
> to code Python to capture these events.  I've scoured the NET but
> cannot find sample code that illustrates capturing events returned by
> an ActiveX control.

http://groups.google.com/groups?q=dispatchwithevents shows
18 relevant posts.  I quote from one of those, which I wrote...:

import win32com.client
from win32com.client import gencache
evmod = gencache.EnsureModule('{D240EC61-B6ED-11D4-9E45-0060B0EB1D67}', 0,
1, 0)

class Evhand:
    def OnOne(self):
        print "eh: One!"
    def OnTwo(self):
        print "eh: Two!"

class Other(evmod._IEvGenEvents2):
    def OnOne(self):
        print "oh: One!"
    def OnTwo(self):
        print "oh: Two!"

ob = win32com.client.DispatchWithEvents("evts.EvGen", Evhand)
oh = Other(ob)
ob.Fire()

where progid 'evts.EvGen' refers to a tiny object I built just
for the purpose of event-handling tests (it generates events
along different sourceinterfaces when you call its Fire method).

This shows we can get events separately from DispatchWithEvents
(and on a different sourceinterface than the default one, if we
know the name of that alternate sourceinterface!).

You probably don't need to handle anything but the default
sourceinterface, so DispatchWithEvents will probably be easier
than subclassing the genpy-generated interface class in your
own Python class -- the latter approach brings in a circular
reference, as you'll see in the messages you'll find in
Google (a few more hits, on the Web rather than on Usenet,
can be found by looking for DispatchWithEvents at www.google.com
rather than groups.google.com, but the info is substantially
the same -- not too different from the docstring for it in
d:\python21\win32com\client\__init__.py (or wherever you keep
your Python installation), which gives a simple example too:

  >>> class IEEvents:
  ...    def OnVisible(self, visible):
  ...       print "Visible changed:", visible
  ...
  >>> ie = DispatchWithEvents("InternetExplorer.Application", IEEvents)
  >>> ie.Visible = 1
  Visible changed: 1


Alex






More information about the Python-list mailing list