codekingpro/portable-devtools
114k
1"""Utilities for working with Connections"""2import pythoncom3import win32com.server.util4 5 6class SimpleConnection:7 "A simple, single connection object"8 9 def __init__(self, coInstance=None, eventInstance=None, eventCLSID=None, debug=0):10 self.cp = None11 self.cookie = None12 self.debug = debug13 if not coInstance is None:14 self.Connect(coInstance, eventInstance, eventCLSID)15 16 def __del__(self):17 try:18 self.Disconnect()19 except pythoncom.error:20 # Ignore disconnection as we are torn down.21 pass22 23 def _wrap(self, obj):24 useDispatcher = None25 if self.debug:26 from win32com.server import dispatcher27 28 useDispatcher = dispatcher.DefaultDebugDispatcher29 return win32com.server.util.wrap(obj, useDispatcher=useDispatcher)30 31 def Connect(self, coInstance, eventInstance, eventCLSID=None):32 try:33 oleobj = coInstance._oleobj_34 except AttributeError:35 oleobj = coInstance36 cpc = oleobj.QueryInterface(pythoncom.IID_IConnectionPointContainer)37 if eventCLSID is None:38 eventCLSID = eventInstance.CLSID39 comEventInstance = self._wrap(eventInstance)40 self.cp = cpc.FindConnectionPoint(eventCLSID)41 self.cookie = self.cp.Advise(comEventInstance)42 43 def Disconnect(self):44 if not self.cp is None:45 if self.cookie:46 self.cp.Unadvise(self.cookie)47 self.cookie = None48 self.cp = None49 