connect.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Utilities for working with Connections"""
  2. import win32com.server.util, pythoncom
  3. class SimpleConnection:
  4. "A simple, single connection object"
  5. def __init__(self, coInstance = None, eventInstance = None, eventCLSID = None, debug = 0):
  6. self.cp = None
  7. self.cookie = None
  8. self.debug = debug
  9. if not coInstance is None:
  10. self.Connect(coInstance , eventInstance, eventCLSID)
  11. def __del__(self):
  12. try:
  13. self.Disconnect()
  14. except pythoncom.error:
  15. # Ignore disconnection as we are torn down.
  16. pass
  17. def _wrap(self, obj):
  18. useDispatcher = None
  19. if self.debug:
  20. from win32com.server import dispatcher
  21. useDispatcher = dispatcher.DefaultDebugDispatcher
  22. return win32com.server.util.wrap(obj, useDispatcher=useDispatcher)
  23. def Connect(self, coInstance, eventInstance, eventCLSID = None):
  24. try:
  25. oleobj = coInstance._oleobj_
  26. except AttributeError:
  27. oleobj = coInstance
  28. cpc=oleobj.QueryInterface(pythoncom.IID_IConnectionPointContainer)
  29. if eventCLSID is None: eventCLSID = eventInstance.CLSID
  30. comEventInstance = self._wrap(eventInstance)
  31. self.cp=cpc.FindConnectionPoint(eventCLSID)
  32. self.cookie = self.cp.Advise(comEventInstance)
  33. def Disconnect(self):
  34. if not self.cp is None:
  35. if self.cookie:
  36. self.cp.Unadvise(self.cookie)
  37. self.cookie = None
  38. self.cp = None