yinkaisheng / Python-UIAutomation-for-Windows

🐍Python 3 wrapper of Microsoft UIAutomation. Support UIAutomation for MFC, WindowsForm, WPF, Modern UI(Metro UI), Qt, IE, Firefox, Chrome ...
Apache License 2.0
2.5k stars 477 forks source link

UIAutomationInitializerInThread is not working #210

Open ughstudios opened 2 years ago

ughstudios commented 2 years ago
def bring_window_to_front(window: HWND):
    with uiautomation.UIAutomationInitializerInThread(True):
        window_handle = uiautomation.ControlFromHandle(window)
        window_handle.SetFocus()

I have the following code and it does not work.

call InitializeUIAutomationInCurrentThread in <Thread(FocusWatcher.update, started daemon 30992)>, inited True

module 'comtypes.gen.UIAutomationClient' has no attribute 'IUIAutomation'
Can not load UIAutomationCore.dll.
1, You may need to install Windows Update KB971513 if your OS is Windows XP, see https://github.com/yinkaisheng/WindowsUpdateKB971513ForIUIAutomation
2, you need to use an UIAutomationInitializerInThread object if use uiautomation in a thread, see demos/uiautomation_in_thread.py

It is failing to initialuze the object IUIAutomation

class _AutomationClient:
    _instance = None

    @classmethod
    def instance(cls) -> '_AutomationClient':
        """Singleton instance (this prevents com creation on import)."""
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def __init__(self):
        tryCount = 3
        for retry in range(tryCount):
            try:
                self.UIAutomationCore = comtypes.client.GetModule("UIAutomationCore.dll")
                self.IUIAutomation = comtypes.client.CreateObject("{ff48dba4-60ef-4201-aa87-54103eef594e}", interface=self.UIAutomationCore.IUIAutomation)
                self.ViewWalker = self.IUIAutomation.RawViewWalker
                #self.ViewWalker = self.IUIAutomation.ControlViewWalker
                break
            except Exception as ex:
                if retry + 1 == tryCount:
                    Logger.WriteLine('''
                self.IUIAutomation = comtypes.client.CreateObject("{ff48dba4-60ef-4201-aa87-54103eef594e}", interface=self.UIAutomationCore.IUIAutomation)

This line is failing: AttributeError("module 'comtypes.gen.UIAutomationClient' has no attribute 'IUIAutomation'")

ughstudios commented 2 years ago

I was able to resolve this by simply calling:

pythoncom.CoInitialize() and pythoncom.CoUninistialize() manually without the context manager