Giter Site home page Giter Site logo

yinkaisheng / python-uiautomation-for-windows Goto Github PK

View Code? Open in Web Editor NEW
2.3K 85.0 462.0 12.17 MB

Python 3 wrapper of Microsoft UIAutomation. Support UIAutomation for MFC, WindowsForm, WPF, Modern UI(Metro UI), Qt, IE, Firefox, Chrome ...

License: Apache License 2.0

Python 100.00% Batchfile 0.01%
python uiautomation windows gui automation

python-uiautomation-for-windows's Introduction

The uiautomation module

🇨🇳中文版介绍

Do not use 3.7.6 and 3.8.1, comtypes doesn't work in these two versions. Install an earlier version or the latest version. enthought/comtypes#202

This module is for UIAutomation on Windows(Windows XP with SP3, Windows Vista, Windows 7 and Windows 8/8.1/10). It supports UIAutomation for the applications which implmented UIAutomation Provider, such as MFC, Windows Form, WPF, Modern UI(Metro UI), Qt(Partly), Firefox(version<=56 or >=60), Chrome and Electron based apps(require --force-renderer-accessibility command line parameter).

I developed it in my spare time and for my personal use.

uiautomation is shared under the Apache Licence 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.

uiautomation1.x supports py2, py3 and doesn't depend on any third package.

uiautomation2.0+ only supports py3 and depends on comtypes and typing(Python3.5+ built-in).
uiautomation2.0+ is not backward compatible with early versions. See API changes.

You can install uiautomation by "pip install uiautomation". After installation, a automation.py that calls uiautomation will be in 'C:\PythonXX\Scripts'. You use this script to traverse UI controls.

Run 'C:\PythonXX\Scripts\automation.py -h' for help.
Run demos\automation_calculator.py to see a simple demo.

On Windows 8/8.1, to automate a Metro App, the app must be in foreground. If a Metro App was switched to background, uiautomation can't fetch its controls' information.

By the way, You should run python as administrator. Otherwise uiautomation may fail to enumerate controls or get controls' information on Windows 7 or higher.

Requirements:

Microsoft UIAutomation Minimum supported client: Windows 7, Windows Vista with SP2 and Platform Update for Windows Vista, Windows XP with SP3 and Platform Update for Windows Vista [desktop apps only]

Microsoft UIAutomation Minimum supported server: Windows Server 2008 R2, Windows Server 2008 with SP2 and Platform Update for Windows Server 2008, Windows Server 2003 with SP2 and Platform Update for Windows Server 2008 [desktop apps only]

C++ dll source code: UIAutomationClient


How to use uiautomation? run 'automation.py -h' help

Understand the arguments of automation.py, and try the following examples:
automation.py -t 0 -n, print current active window's controls, show fullname
automation.py -r -d 1 -t 0, print desktop(the root of control tree) and it's children(top level windows)

top level windows

automation.py prints the properties of controls and the patterns they support. You use controls and patterns to get controls' information and operate them.

A control should support some patterns or conditionally supports some patterns according to its control type.

patterns

Refer Control Pattern Mapping for UI Automation Clients for the cpmplete control pattern table.

uiautomation searches controls from the control tree based on the controls' properties you supply.

Suppose the control tree is

root(Name='Desktop', Depth=0)
  window1(Depth=1)
    control1-001(Depth=2)
    control1-...(Depth=2)
    ...
    control1-100(Depth=2)
  window2(Name='window2', Depth=1)
    control2-1(Depth=2)
      control2-1-001(Depth=3)
      control2-1-...(Depth=3)
      ...
      control2-1-100(Depth=3)
    control2-2(Depth=2)
    control2-3(Depth=2)
    control2-4(Name='2-4', Depth=2)
      editcontrol(Name='myedit1', Depth=3)
      editcontrol(Name='myedit2', Depth=3)

If you want to find the EditControl whose name is 'myedit2' and type 'hi',
you can write the following code:

uiautomation.EditControl(searchDepth=3, Name='myedit2').SendKeys('hi')

But this code run slowly because there are more than 200 controls before myedit2 in the control tree.
uiautomation has to traverse more than 200 controls before finding myedit2 if search from root in 3 search depth.
The better is:

window2 = uiautomation.WindowControl(searchDepth=1, Name='window2') # search 2 times
sub = window2.Control(searchDepth=1, Name='2-4')    # search 4 times
edit = sub.EditControl(searchDepth=1, Name='myedit2')   # search 2 times
edit.SendKeys('hi')

This code run faster than the former.
You can also combine the four lines code into one line.

uiautomation.WindowControl(searchDepth=1, Name='window2').Control(searchDepth=1, Name='2-4').EditControl(searchDepth=1, Name='myedit2').SendKeys('hi')

Now let's take notepad.exe for an example.
Luanch notepad.exe and run automation.py -t 3, then swith to Notepad and wait for 5 seconds

automation.py will print the controls of Notepad and save them to @AutomationLog.txt:

ControlType: PaneControl ClassName: #32769 Name: 桌面 Depth: 0 (Desktop window, the root control)
  ControlType: WindowControl ClassName: Notepad Depth: 1 (Top level window)
    ControlType: EditControl ClassName: Edit Depth: 2
      ControlType: ScrollBarControl ClassName: Depth: 3
        ControlType: ButtonControl ClassName: Depth: 4
        ControlType: ButtonControl ClassName: Depth: 4
      ControlType: ThumbControl ClassName: Depth: 3
    ControlType: TitleBarControl ClassName: Depth: 2
      ControlType: MenuBarControl ClassName: Depth: 3
        ControlType: MenuItemControl ClassName: Depth: 4
      ControlType: ButtonControl ClassName: Name: 最小化 Depth: 3 (Minimize Button)
      ControlType: ButtonControl ClassName: Name: 最大化 Depth: 3 (Maximize Button)
      ControlType: ButtonControl ClassName: Name: 关闭 Depth: 3 (Close Button)
...

Run the following code

# -*- coding: utf-8 -*-
# this script only works with Win32 notepad.exe
# if you notepad.exe is the Windows Store version in Windows 11, you need to uninstall it.
import subprocess
import uiautomation as auto

def test():
    print(auto.GetRootControl())
    subprocess.Popen('notepad.exe', shell=True)
    # you should find the top level window first, then find children from the top level window
    notepadWindow = auto.WindowControl(searchDepth=1, ClassName='Notepad')
    if not notepadWindow.Exists(3, 1):
        print('Can not find Notepad window')
        exit(0)
    print(notepadWindow)
    notepadWindow.SetTopmost(True)
    # find the first EditControl in notepadWindow
    edit = notepadWindow.EditControl()
    # usually you don't need to catch exceptions
    # but if you meet a COMError exception, put it in a try block
    try:
        # use value pattern to get or set value
        edit.GetValuePattern().SetValue('Hello')# or edit.GetPattern(auto.PatternId.ValuePattern)
    except auto.comtypes.COMError as ex:
        # maybe you don't run python as administrator 
        # or the control doesn't have a implementation for the pattern method(I have no solution for this)
        pass
    edit.SendKeys('{Ctrl}{End}{Enter}World')
    print('current text:', edit.GetValuePattern().Value)
    # find the first TitleBarControl in notepadWindow, 
    # then find the second ButtonControl in TitleBarControl, which is the Maximize button
    notepadWindow.TitleBarControl().ButtonControl(foundIndex=2).Click()
    # find the first button in notepadWindow whose Name is '关闭', the close button
    # the relative depth from Close button to Notepad window is 2
    notepadWindow.ButtonControl(searchDepth=2, Name='关闭').Click()
    # then notepad will popup a window askes you to save or not, press hotkey alt+n not to save
    auto.SendKeys('{Alt}n')

if __name__ == '__main__':
    test()

auto.GetRootControl() returns the root control(the Desktop window)
auto.WindowControl(searchDepth=1, ClassName='Notepad') creates a WindowControl, the parameters specify how to search the control
the following parameters can be used
searchFromControl = None,
searchDepth = 0xFFFFFFFF,
searchInterval = SEARCH_INTERVAL,
foundIndex = 1
Name
SubName
RegexName
ClassName
AutomationId
ControlType
Depth
Compare

See Control.__init__ for the comments of the parameters.
See scripts in folder demos for more examples.

Control.Element returns the low level COM object IUIAutomationElement, Almost all methods and properties of Control are implemented via IUIAutomationElement COM API and Win32 API. when calling a control's method or property that indirectly calls Control.Element and Control.Element is None, uiautomation starts to search the control by the properties you supply. uiautomation will raise a LookupError exception if it can't find the control in uiautomation.TIME_OUT_SECOND(default 10 seconds). Control.Element will has a valid value if uiautomation finds the control successfully. You can use Control.Exists(maxSearchSeconds, searchIntervalSeconds) to check whether a control Exists, this function doesn't raise any exception. Call Control.Refind or Control.Exists to make Control.Element invalid again and uiautomation will starts a new search.

For example:

#!python3
# -*- coding:utf-8 -*-
# this script only works with Win32 notepad.exe
# if you notepad.exe is the Windows Store version in Windows 11, you need to uninstall it.
import subprocess
import uiautomation as auto
auto.uiautomation.SetGlobalSearchTimeout(15)  # set new timeout 15


def main():
    subprocess.Popen('notepad.exe', shell=True)
    window = auto.WindowControl(searchDepth=1, ClassName='Notepad')
    # or use Compare for custom search
    # window = auto.WindowControl(searchDepth=1, ClassName='Notepad', Compare=lambda control,depth:control.ProcessId==100)
    edit = window.EditControl()
    # when calling SendKeys, uiautomation starts to search window and edit in 15 seconds
    # because SendKeys indirectly calls Control.Element and Control.Element is None
    # if window and edit don't exist in 15 seconds, a LookupError exception will be raised
    try:
        edit.SendKeys('first notepad')
    except LookupError as ex:
        print("The first notepad doesn't exist in 15 seconds")
        return
    # the second call to SendKeys doesn't trigger a search, the previous call makes sure that Control.Element is valid
    edit.SendKeys('{Ctrl}a{Del}')
    window.GetWindowPattern().Close()  # close the first Notepad, window and edit become invalid even though their Elements have a value

    subprocess.Popen('notepad.exe')  # run second Notepad
    window.Refind()  # need to refind window, trigger a new search
    edit.Refind()  # need to refind edit, trigger a new search
    edit.SendKeys('second notepad')
    edit.SendKeys('{Ctrl}a{Del}')
    window.GetWindowPattern().Close()  # close the second Notepad, window and edit become invalid again

    subprocess.Popen('notepad.exe')  # run third Notepad
    if window.Exists(3, 1): # trigger a new search
        if edit.Exists(3):  # trigger a new search
            edit.SendKeys('third notepad')  # edit.Exists makes sure that edit.Element has a valid value now
            edit.SendKeys('{Ctrl}a{Del}')
        window.GetWindowPattern().Close()
    else:
        print("The third notepad doesn't exist in 3 seconds")


if __name__ == '__main__':
    main()

If automation.py can't print the controls you see. Maybe the controls were built by DirectUI(or CustomControl), not UI Frameworks supplied by Microsoft. In order to support UIAutomation, an UI Framework must implement UI Automation Provider.

A Microsoft UI Automation provider is a software object that exposes an element of an application's UI so that accessibility client applications can retrieve information about the element and invoke its functionality. In general, each control or other distinct element in a UI has a provider.

Microsoft includes a provider for each of the standard controls that are supplied with Microsoft Win32, Windows Forms, and Windows Presentation Foundation (WPF). This means that the standard controls are automatically exposed to UI Automation clients; you do not need to implement any accessibility interfaces for the standard controls.

If your application includes any custom controls, you need to implement UI Automation providers for those controls to make them accessible to accessibility client applications. You also need to implement providers for any third party controls that do not include a provider. You implement a provider by implementing UI Automation provider interfaces and control pattern interfaces.


Another UI tool Inspect.exe supplied by Microsoft can also be used to traverse the UI elements. It has an UI interface while my script shows UI elements in terminal. But I found that my script is more convenient sometimes.

Inspect


Some screenshots:

Batch rename pdf bookmark bookmark

Microsoft Word
Word

Wireshark 3.0 (Qt 5.12) Wireshark

GitHub Desktop (Electron App) GitHubDesktop

Pretty print dir
PrettyPrint

Donate:
微信 支付宝

python-uiautomation-for-windows's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-uiautomation-for-windows's Issues

Cannot run on Win10(works well on Win8.1)

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

RESTART: C:\Users\yanglei2\Desktop\Python-UIAutomation-for-Windows-master\automation_notepad_py3.py
Traceback (most recent call last):
File "C:\Users\yanglei2\Desktop\Python-UIAutomation-for-Windows-master\automation_notepad_py3.py", line 7, in
import uiautomation as automation
File "C:\Users\yanglei2\Desktop\Python-UIAutomation-for-Windows-master\uiautomation.py", line 55, in
_automationClient = AutomationClient()
File "C:\Users\yanglei2\Desktop\Python-UIAutomation-for-Windows-master\uiautomation.py", line 43, in init
self.dll = ctypes.cdll.UIAutomationClientX86
File "C:\Users\yanglei2\AppData\Local\Programs\Python\Python35-32\lib\ctypes_init
.py", line 417, in getattr
dll = self.dlltype(name)
File "C:\Users\yanglei2\AppData\Local\Programs\Python\Python35-32\lib\ctypes_init
.py", line 347, in init
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] 找不到指定的模块。

Adding ProcessId property to Control class

Hi !

I tried to add ProcessId property

class Control():
 @property
    def ProcessId(self):
        '''Return process id'''
        return ClientObject.dll.GetProcessId(self.Element)

and when I call the property I got this error message

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\python27\lib\ctypes\__init__.py", line 378, in __getattr__
    func = self.__getitem__(name)
  File "C:\python27\lib\ctypes\__init__.py", line 383, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'GetElementProcessId' not found

如何恢复最小化的窗口

我的使用场景是用脚本检测某个窗口是否在最前面,如果不在,就检查是否被最小化了,如果不是被最小化,就起一个新的窗口。如果已有窗口,就进行下一步活动。

现在我已经可以检查出窗口被最小化了,但没有办法调到最前面。
那个窗体是个Qt5的pannel

无论我用panel.Show() 还是 panel.SetFocus()还是一起使用都不能恢复窗体,请问是不是我的使用方法不对?

Control.CaptureToImage(path) black screenshot UWP Apps

The CaptureToImage() method doesn't work with UWP application. It takes black screenshots.
For "ApplicationFrameWindow" Class Name.

---- Code ---- (Exp:)
import uiautomation as uiauto calculatorWindow = uiauto.WindowControl(Name="Calculator") # The UWP calculator app calculatorWindow.CaptureToImage("d:\\captureCalculatorWindowControl.png")
---- Result ----
capturecalculatorwindowcontrol

capture

Win10系统下,多线程中控件获取不到

Win7系统下程序执行一切正常,放在Win10系统下程序就会卡住,调试后发现在多线程中控件获取不到,一直处于Connect的状态,比如这样一句代码:automation.WindowControl(searchDepth=1, AutomationId='', Name=‘'),不放在线程中执行可以获取到控件,一旦放在线程中执行这样一句代码程序就会卡住,一直处于Connect的状态,不知道是什么原因,请老师指教,谢谢!

询问下如何获取窗口名称和控件名称

大神,
谢谢你的这套框架,有几个问题想问下:
1. 如过我新安装了一个程序,比如可执行文件是"abc.exe",我可以如何打开它
2.如果这是一个.net写的程序,但是没有源代码,我要如何知道它某个窗口和控件的名字?
3.如果程序不是.net写的,依然可以用这套框架吗?可以怎样知道窗口和控件的名字?

非常感谢了!!!

一些场景无法解决的问题

日志会再补上

场景1:利用windows任务计划执行,UI自动化的脚本无法执行,会报寻找控件超时的错误
场景2:利用time.sleep() 一段时间,当电脑锁屏后也无法执行UI自动化

有没有办法解决

AttributeError: '_AutomationClient' object has no attribute 'dll'

Hi,

I am trying to set the module on Windows 10. I am running a python script to open the Notepad and with admin rights, but i received the below log. Am I missing something that needs to be done with the DLL files of the library?

AutomationClientX86.dll
AutomationClientX64.dll

Are these files already present or should be manually included in the system path?

Traceback (most recent call last):
  File "automate.py", line 2, in <module>
    import uiautomation as automation
  File "C:\Users\anant.pande\AppData\Roaming\Python\Python35\site-packages\uiautomation.py", line 55, in <module>
    _automationClient = _AutomationClient()
  File "C:\Users\anant.pande\AppData\Roaming\Python\Python35\site-packages\uiautomation.py", line 45, in __init__
    self.dll = ctypes.cdll.UIAutomationClientX64
  File "<C:\Program Files\Anaconda3\lib\ctypes\__init__.py>", line 417, in __getattr__
    dll = self._dlltype(name)
  File "<C:\Program Files\Anaconda3\lib\ctypes\__init__.py>", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found
Exception ignored in: <bound method _AutomationClient.__del__ of <uiautomation._AutomationClient object at 0x000002BF64E952E8>>
Traceback (most recent call last):
  File "C:\Users\anant.pande\AppData\Roaming\Python\Python35\site-packages\uiautomation.py", line 52, in __del__
    self.dll.ReleaseInstance()
AttributeError: '_AutomationClient' object has no attribute 'dll' 

版本1.1.8 所写的代码无法在1.1.12上运行

image
Traceback (most recent call last):
File "D:/hqzf_ui_test/cases/sample.py", line 52, in
menu_item.MoveCursorToMyCenter()
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2676, in MoveCursorToMyCenter
return self.MoveCursor(simulateMove = simulateMove)
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2657, in MoveCursor
left, top, right, bottom = self.BoundingRectangle
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2643, in BoundingRectangle
_AutomationClient.instance().dll.GetElementBoundingRectangle(ctypes.c_size_t(self.Element), ctypes.byref(rect))
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2561, in Element
self.Refind(maxSearchSeconds = TIME_OUT_SECOND, searchIntervalSeconds = self.searchWaitTime)
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2546, in Refind
if not self.Exists(maxSearchSeconds, searchIntervalSeconds):
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2515, in Exists
if prev and not prev._element and not prev.Exists(maxSearchSeconds, searchIntervalSeconds):
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2518, in Exists
control = FindControl(self.searchFromControl, self._CompareFunction, self.searchDepth, False, self.foundIndex)
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 4407, in FindControl
if compareFunc(child, depth):
File "C:\Users\admin\AppData\Roaming\Python\Python36\site-packages\uiautomation\uiautomation.py", line 2488, in _CompareFunction
raise KeyError('unsupported argument: {} in {} constructor'.format(key, self.class.name))
KeyError: 'unsupported argument: LocalizedControlType in MenuControl constructor'

再读又是一个数字海洋!

automation.py 的代码改了这么多啊, 今天一看差距太大了,看来我在Python上的道路还有很远啊,膜拜大神!但是好像还是不能实现我想要的事情,没事看看对自己也好!

The SetTopmost method does not work as expected always.

Hello yinkaisheng,
This project is fantastic and I think it could really repalce the QTP. However, I found the SetTopmost method not always work as expected when running the demo of notepadtop.py. Here are the reproducing steps:

  1. Open a notepad and minimize it.
  2. Run notepadtop.py.

the definition of SetWindowTopmost(hWnd, isTopmost) is:
topValue = SWP.HWND_TOPMOST if isTopmost else SWP.HWND_NOTOPMOST
return Win32API.SetWindowPos(hWnd, topValue, 0, 0, 0, 0, SWP.SWP_NOSIZE|SWP.SWP_NOMOVE)

I think it's better to change to:
topValue = ShowWindow.Restore if isTopmost else ShowWindow.Hide
Win32API.ShowWindow(hWnd, topValue)
if isTopmost:
Win32API.SetForegroundWindow(hWnd)

同个UI中有兩相同的Control

你好,剛接觸到自動測試領域,還在摸索中,看到你的代碼對我很有幫助
有碰到幾個問題想請問下:
當同個UI頁面有兩相通的控件類型,除了Rect位置不一樣,其餘信息完全相同,該如何選定正確的控件進行控制?
(例如:一頁面有兩ScrollBarControl
ControlType: ScrollBarControl ClassName: AutomationId: NonClientVerticalScrollBar Rect: (176, 193, 193, 715) Name: 垂直滚动条 Handle: 0x0(0) Depth: 7 ProcessId:7828 RangeValue: 0

ControlType: ScrollBarControl ClassName: LineVScrollBar AutomationId: VerticalScrollBar Rect: (1349, 193, 1366, 715) Name: 垂直滚动条 Handle: 0x410A5A(4262490) Depth: 7 ProcessId:7828 RangeValue: 0)
謝謝!

Border Control not visible by uiautomation library

Hi,

I'm doing test automation for a UWP application, each icon of the application is covered by "Border" control. However, "BorderControl"s are not detected by UIautomation,
What i'm doing is adding the "BorderControl" widget type to uiautomation, but it doesn't work!
Someone have any suggestions?

Thanks,

There is some trouble with AutomationClient.dll has been loaded

Hi Kaisheng,

In win10, it will show the "WindowsError: [Error 126] The specified module could not be found" hints after processed "import uiautomation as automation";

I took my attention with KB971513 patch but that would not fit to win10. Specially, on another win10 machine, that works well and didn't pop-up any error hint.

I guess there is something incompatible with UIAutomationClient.dll but have no idea to fix it;
If you are free please have a look at it.
Thanks.

您好~无法在win10 32位上点击坐标

场景:打开360杀毒,点击更新。
版本:win10 32
详细描述:可以打开360杀毒主窗口,并且识别到主窗口的Lt, Rt, Lb, Rb,但是点击“检查更新”(日志和设置也测试过),鼠标没有反应。
上述操作在 win10 64 和win8 64 上均可以正常识别并点击。
请问大大,这个问题大概是什么原因?很久不得其解。

pip install?

Any plans to support installing as a library, with pip install?

Expand() method not work in class ComboBoxControl as report "ExpandCollapsePattern not supported"

while I want to choose a value from a combobox, in my .net application, I found the "IsExpandCollapsePatternAvailable" value in the Inspect was "false".
so while I run
automation.ComboBoxControl(searchFromControl=blablabla, ClassName=‘blablabla').Select(value)
it failed as in class ComboBoxControl(), method Select(), the code is self.Expand().

and I just make a workaround that replace self.Expand() with self.Click(), and it works

later, I tried to not break your original code, so add an "if" in Select() method:

    if self.IsExpandCollapsePatternAvailable():
        self.Expand()
    else:
        self.Click()

and add one property to get the IsExpandCollapsePatternAvailable value

def IsExpandCollapsePatternAvailable(self):
    '''Return bool'''
    return _automationClient.dll.GetElementIsExpandCollapsePatternAvailable(self.Element)

but it reports not found error

if self.IsExpandCollapsePatternAvailable():
File "D:\Tools\Python\Python-UIAutomation-for-Windows\automation.py", line 1585, in IsExpandCollapsePatternAvailable
return automationClient.dll.GetElementIsExpandCollapsePatternAvailable(self.Element)
File "C:\Python27\lib\ctypes__init
_.py", line 378, in getattr
func = self.getitem(name)
File "C:\Python27\lib\ctypes__init__.py", line 383, in getitem
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'GetElementIsExpandCollapsePatternAvailable' not found

how do I know the functions detail in the _automationClient.dll ?

DragDrop 函数会有偏差

我用windows画图做一个实验时发现,鼠标位置与期待的不符,我把画图软件打开并最大化,然后直接调用库中的的DragDrop函数,就像这样 DragDrop(200, 200, 1000, 1000, 2)。这样子会成功的画出一条直线,但是该直线的末端比我的光标多出了一截
就像这样
image

估计是在DragDrop函数内,为了实现duration功能丢失了精度问题。

Get text under mouse in Microsoft Word Document?

This is a question about use.

I would like to discover text under mouse on applications as Microsoft Word or Outlook. Usually I get this info with
control = ControlFromCursor()
text = control.Name+"="+control.CurrentValue()

But inside the main text content (page document) dont information about text content, and dont appear any other control inside (no more deepth)

I have discover that with inspector tool over a opened Word document, you can get info about pages, and even the paragraph parts inside pages, but dont appear any text values at alll. But I have discover that you can get the really text inside paragraphs with the option menu:
Inspector>Action>Text Pattern Explorer
With this, it appear a new window that let you navigate around the document and get info of text in every form (paragraph).

Coul you help me how to get this same with your ui-automation? I cant figure how to make this exploring
I have the same problem inside the mail content in Outlook application.

Thanks in advance for this really great tool.

选择第二个ComboBox的时候无法选择上

subprocess.Popen('MessageBox.exe')
print(automation.GetRootControl())

Form= automation.WindowControl(searchDepth = 1,ClassName = "Window",Name="MainWindow")
Form.EditControl(AutomationId='messageBoxText').Click()
Form.EditControl(AutomationId='caption').Click()

ownerCheckBox=Form.CheckBoxControl(AutomateionId='ownerCheckBox')

Form.ComboBoxControl(AutomateionId="buttonComboBox").Select('YesNo')
#第一个能选择上

Form.ComboBoxControl(AutomateionId="imageComboBox").Select('Stop') Form.ComboBoxControl(AutomateionId="defaultResultComboBox").Select('Yes')
Form.ComboBoxControl(AutomateionId="optionsComboBox",).Select('RightAlign')
#这三个都不能成功操作
txtName=Form.ButtonControl(AutomationId="showMessageBoxButton").Click()

你的例子存在问题

你的例子里调用SetActive(),不对, 你的例子错了,你的源码中这个SetActive()方法是写在WindowControl这个类里的, 你的调用没有从这个类里继承,就会报错~!

获取控件卡死

我在运行您的那个 uiautomation.py 如果我不调用最后的EnumAndLogControl 这个函数程序并不会正常退出而是出现假死 (部分窗口控件)

UTF-16 encode/decode issue

Hey bro! Thanks for your script. But

I got an issue, I was going to install Intel RealSense SDK core installer but your automation.py does not capture any controls of this window. I got this error message
image

This is the windows I need to interact
image

I guess it includes character ™ and ®so it does not work.

Help documents

Hi Yang, it is great project! where can I get the help documents for the development?

Library Errors out before timeout to find a control not yet present with KeyError: 0

Traceback (most recent call last):
File "init.py", line 120, in wait_for_control
if control.Exists(search_wait_time, uiautomation.SEARCH_INTERVAL):
File "C:\Python27\Lib\site-packages\uiautomation\uiautomation.py", line 2424, in Exists
control = FindControl(self.searchFromControl, self._CompareFunction, self.searchDepth, False, self.foundIndex)
File "C:\Python27\Lib\site-packages\uiautomation\uiautomation.py", line 4299, in FindControl
for child, depth in WalkControl(control, findFromSelf, maxDepth):
File "C:\Python27\Lib\site-packages\uiautomation\uiautomation.py", line 4185, in WalkControl
child = lastControl.GetFirstChildControl()
File "C:\Python27\Lib\site-packages\uiautomation\uiautomation.py", line 2670, in GetFirstChildControl
return Control.CreateControlFromElement(comEle)
File "C:\Python27\Lib\site-packages\uiautomation\uiautomation.py", line 2790, in CreateControlFromElement
return ControlDictcontrolType

你好, 支持微信pc客户端吗? 貌似不行。

2017-06-23 04:03:28.451 Function: main, Line: 4207 -> Starts, Current Cursor Position: (867, 465)
ControlType: WindowControl ClassName: ChatWnd AutomationId: Rect: (1084, 22, 1909, 982) Name: test1 Handle: 0xF2394(992148) Depth: 0
ControlType: PaneControl ClassName: popupshadow AutomationId: Rect: (1065, 3, 1928, 1001) Name: Handle: 0x72362(467810) Depth: 1
ControlType: PaneControl ClassName: ChatContactMenu AutomationId: Rect: (-10000, -10000, -9999, -9999) Name: ChatContactMenu Handle: 0x82348(533320) Depth: 1
ControlType: PaneControl ClassName: popupshadow AutomationId: Rect: (-10019, -10019, -9980, -9980) Name: Handle: 0x62396(402326) Depth: 2
2017-06-23 04:03:28.484 Function: main, Line: 4238 -> Ends

How to get the ExpandCollapseState?

Hi
in your last commit, you update the ExpandCollapseState() class, and I can see this state value for a TreeItemControl in Inspect.exe, but is that any method to get this state?
I want to try to get all the TreeItemControls and loop calling Expand() until it's a LeafNode.

or shall I use walkTree() to get all of them? I tried, but walkTree() will use getChildrenFunc/getFirstChildFunc/getNextSiblingFunc, but if the tree was not expanded, all are None.

Some recommendations...

1 - Global waiting gap

eg. I want to get all the operations like Click/DoubleClick/InvokePattern.Invoke/... to wait for few seconds after each operation, for just like 1 second waiting for each operation, need a parameter in global to have it configured.

2 - Control search code style

I used to be used with UFT, which has the code style like:
CheckBoxControl("AutoId1").HeaderControl("AutoId2").ButtonControl("AutoId3").Click()
AutomationId is default search parameter

Currently I need to write above code like following:
CheckBoxControl(searchFromControl=HeaderControl(searchFromControl=ButtonControl(searchFromControl=IEWindow, AutomationId = "AutoId1"),AutomationId = "AutoId2"),AutomationId="AutoId3").Click()

3 - Wait for some element available or exists function

Just like WaitForExist(SomeControl, timeout)
It can wait for the control to be existed in appointed timeout value. Another enhancement is WaitForDisappear(SomeControl, timeout), all returns a bool

Is is possible to have it?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.