如何将参数传递给win32com事件处理程序

问题描述:

下面的代码正常工作。我无法找到将某些参数传递到EventHandler或从EventHandler调用MainClass的方法的方法。例如,而不是使用常量param,我想通过构造函数或setter方法传递它。我试过here的建议。但在这种情况下,EventHandler实例不会捕获任何事件(或者至少在stdout中没有显示任何内容)。如何将参数传递给win32com事件处理程序

class EventHandler: 
    param = "value"  
    def OnConnected(self): 
     print 'connected' 
     return True 

class MainClass: 
    def run(self): 
     pythoncom.CoInitialize() 
     session = win32com.client.Dispatch("Lib.Obj") 
     session_id = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, session) 
     args = { 's_id': session_id, } 
     thread = threading.Thread(target=self.run_in_thread, kwargs=args) 
     thread.start() 

    def run_in_thread(self, s_id): 
     pythoncom.CoInitialize() 
     session = win32com.client.DispatchWithEvent(
      pythoncom.CoGetInterfaceAndReleaseStream(s_id, pythoncom.IID_IDispatch), 
      EventHandler 
     ) 
     session.connect() 
     while True: 
      pythoncom.PumpWaitingMessages() 
      time.sleep(1) 

if __name__ == '__main__': 
    obj = MainClass() 
    obj.run() 
+0

在这里阅读我的答案,这应该可以解决您的问题: http://*.com/questions/23341675/passing-additional-arguments-to-python-callback-object-win32com-client-dispatch/41140003#41140003 – Vlad

一种可能性是使用WithEvents函数。但这可能不是最好的方法。现在handlerclient对象是不同的实体,所以这导致它们之间的其他交互机制。

class EventHandler: 

    def set_params(self, client): 
     self.client = client 

    def OnConnected(self): 
     print "connected!" 
     self.client.do_something() 
     return True 

client = win32com.client.Dispatch("Lib.Obj") 
handler = win32com.client.WithEvents(client, EventHandler) 
handler.set_client(client) 

client.connect() 

while True: 
    PumpWaitingMessages() 
    time.sleep(1) 

这里是a complete example