2015-10-19 133 views
2

下面的代碼正常工作。我無法找到將某些參數傳遞到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://stackoverflow.com/questions/23341675/passing-additional-arguments-to-python-callback-object-win32com-client-dispatch/41140003#41140003 – Vlad

回答

1

一種可能性是使用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

相關問題