有没有一种方法可以将MS UIAutomation.dll导入Python?

时间:2019-12-19 20:39:07

标签: python dll ui-automation dllimport win32com

我正在使用win32com导入,并且一直在研究win32api和win32gui导入,同时使用默认的Office程序(例如Excel,Outlook等)自动执行各种过程。我的问题是,有没有办法访问已经是否安装了UIAutomation.dll和其他标准dll并导入它们或使用它们在Python中创建我自己的自定义模块?我目前在Windows 10上使用Python 3.7。

2 个答案:

答案 0 :(得分:0)

从某种意义上说

首先,使用以下命令从命令提示符安装Python模块:

pip install uiautomation

您可以通过右键单击Windows图标并根据需要选择“命令提示符(管理员)”来为所有人安装它。

要在Python中使用此产品,最常用的语句是:

import uiautomation

这将使模块中的所有项目均可用于脚本。例如,您可以访问

uiautomation.CalendarControl

使用常规的Python语法。

答案 1 :(得分:0)

我对这个问题找到了自己的答案。您可以使用'comtypes.client'和'ctypes'模块导入整个UIAutomationCore.dll库以及任何其他本机DLL或库。对于没有团队导入/ pip安装限制和安全问题的人员,这是指向已包装且功能齐全的导入的链接。如果像我一样,您只需要默认使用Anacoda3安装随附的“本机”导入和库。然后,我建议使用此代码来开始您自己进行包装,就像我为特定需要所做的那样。希望这可以帮助其他人使用UIAutomationCore。

链接:[https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/master/uiautomation/uiautomation.py][1]

代码:

import os
import sys
from typing import (Any, Callable, Iterable, Tuple, List, Dict)  # need pip install typing for Python3.4 or lower
import ctypes
import ctypes.wintypes
import comtypes
import comtypes.client

TreeNode = Any

METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow'  # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5  # search control interval seconds
MAX_MOVE_SECOND = 0.5  # simulate mouse move or drag max seconds
TIME_OUT_SECOND = 20
OPERATION_WAIT_TIME = 0.5
MAX_PATH = 260
DEBUG_SEARCH_TIME = False
DEBUG_EXIST_DISAPPEAR = False
S_OK = 0

IsNT6orHigher = os.sys.getwindowsversion().major >= 6
ProcessTime = time.perf_counter  #this returns nearly 0 when first call it if python version <= 3.6
ProcessTime()  # need to call it once if python version <= 3.6


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):
        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
        except OSError as ex:
            Logger.WriteLine('Can not load UIAutomationCore.dll.\nYou may need to install Windows Update KB971513.\nhttps://github.com/yinkaisheng/WindowsUpdateKB971513ForIUIAutomation', ConsoleColor.Yellow)
            raise ex
        #Windows dll
        ctypes.windll.user32.GetClipboardData.restype = ctypes.c_void_p
        ctypes.windll.user32.GetWindowDC.restype = ctypes.c_void_p
        ctypes.windll.user32.OpenDesktopW.restype = ctypes.c_void_p
        ctypes.windll.user32.WindowFromPoint.restype = ctypes.c_void_p
        ctypes.windll.user32.SendMessageW.restype = ctypes.wintypes.LONG
        ctypes.windll.user32.GetForegroundWindow.restype = ctypes.c_void_p
        ctypes.windll.user32.GetWindowLongW.restype = ctypes.wintypes.LONG
        ctypes.windll.kernel32.GlobalLock.restype = ctypes.c_void_p
        ctypes.windll.kernel32.GlobalAlloc.restype = ctypes.c_void_p
        ctypes.windll.kernel32.GetStdHandle.restype = ctypes.c_void_p
        ctypes.windll.kernel32.OpenProcess.restype = ctypes.c_void_p
        ctypes.windll.kernel32.CreateToolhelp32Snapshot.restype = ctypes.c_void_p


class _DllClient:
    _instance = None

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

    def __init__(self):
        binPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bin")
        os.environ["PATH"] = binPath + os.pathsep + os.environ["PATH"]
        load = False
        if sys.maxsize > 0xFFFFFFFF:
            try:
                self.dll = ctypes.cdll.UIAutomationClient_VC140_X64
                load = True
            except OSError as ex:
                pass
        else:
            try:
                self.dll = ctypes.cdll.UIAutomationClient_VC140_X86
                load = True
            except OSError as ex:
                pass
        if load:
            self.dll.BitmapCreate.restype = ctypes.c_size_t
            self.dll.BitmapFromWindow.argtypes = (ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int)
            self.dll.BitmapFromWindow.restype = ctypes.c_size_t
            self.dll.BitmapFromFile.argtypes = (ctypes.c_wchar_p, )
            self.dll.BitmapFromFile.restype = ctypes.c_size_t
            self.dll.BitmapToFile.argtypes = (ctypes.c_size_t, ctypes.c_wchar_p, ctypes.c_wchar_p)
            self.dll.BitmapRelease.argtypes = (ctypes.c_size_t, )
            self.dll.BitmapGetWidthAndHeight.argtypes = (ctypes.c_size_t, )
            self.dll.BitmapGetPixel.argtypes = (ctypes.c_size_t, ctypes.c_int, ctypes.c_int)
            self.dll.BitmapSetPixel.argtypes = (ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_uint)

            self.dll.Initialize()
        else:
            self.dll = None
            Logger.WriteLine('Can not load dll.\nFunctionalities related to Bitmap are not available.\nYou may need to install Microsoft Visual C++ 2010/2015 Redistributable Package.', ConsoleColor.Yellow)
    def __del__(self):
        if self.dll:
            self.dll.Uninitialize()