How to pass arguments to win32com event handler

自闭症网瘾萝莉.ら 提交于 2019-12-24 03:41:34

问题


The code below works fine. I can't find a way to pass some arguments to EventHandler or to call methods of MainClass from EventHandler. For example instead of using constant param, I'd like to pass it through constructor or setter method. I've tried recommendations from here. But in this case EventHandler instance does not catch any events (or at least nothing appears in stdout).

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() 

回答1:


One possibility is to use WithEvents function. But this may not be the best way. Also now handler and client objects are different entities, so this leads to additional mechanisms of interaction between them.

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)

Here is a complete example.



来源:https://stackoverflow.com/questions/33208969/how-to-pass-arguments-to-win32com-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!