예제 #1
0
 def calDemo(self):
     app = Application(backend="uia").start('calc.exe')
     dlg = Desktop(backend="uia").Calculator
     dlg.type_keys('2*3=')
     dlg.print_control_identifiers()
     dlg.minimize()
     Desktop(backend="uia").window(title='Calculator',
                                   visible_only=False).restore()
class Win10CalcTest:

    app = None
    dlg = None

    def __init__(self):
        self.app = Application(backend="uia").start('calc.exe')
        self.dlg = Desktop(backend="uia").Calculator

    def keyboard_input(self, input_string):
        self.dlg.type_keys(input_string)

    def validate_result(self, expected_string):
        result = self.dlg.child_window(auto_id="CalculatorResults").texts()[0]
        if str(result) == 'Display is ' + expected_string:
            print(f"Result {result} is the expected one!")
        else:
            raise AssertionError(f"Result {result} is different than expected {expected_string}")

    def press_buttons(self, button_name):
        button = self.dlg.child_window(auto_id=button_name+'Button')
        button.click()

    def close_calculator(self):
        close_button = self.dlg.child_window(auto_id='Close')
        close_button.click()
        self.dlg.close()

    def verify_calculator_is_opened(self, expected):
        try:
            if expected:
                return self.dlg.child_window(auto_id="CalculatorResults").wait('visible', 5)
            else:
                return self.dlg.child_window(auto_id="CalculatorResults").wait_not('visible', 5)
        except ElementNotFoundError:
            if expected:
                return False
            else:
                return True
예제 #3
0
def pywinauto_demo():
    from pywinauto import Application, Desktop

    # 获取应用对象
    # 三种方式任选一种
    # 方式一:应用进程pid(连接)
    # pid= 12492
    # app = Application(backend='uia').connect(process=pid)
    # # 方式二:应用完整路径(连接)
    # app = Application(backend='uia').connect(path="D:\Program Files (x86)\Tencent\WeChat\WeChat.exe")
    # # 方式三:打开应用(打开)
    # app = Application(backend='uia').start('D:\Program Files (x86)\Tencent\WeChat\WeChat.exe')

    app = Application(backend="uia").start('calc.exe')

    dlg = Desktop(backend="uia").计算器  # window specification
    dlg.type_keys('2*3=')
    dlg.print_control_identifiers()  # this is also window spec method

    dlg.minimize()
    # minimized window needs some tricks to find it and restore
    Desktop(backend="uia").window(title='计算器', visible_only=False).restore()
# Nicholas DeMello
# WhatsApp Spam Bot

from pywinauto import Desktop

WhatsApp = Desktop(backend='uia').WhatsApp
#WhatsApp.print_control_identifiers()		# Find appropriate child_window
target = WhatsApp.child_window(title_re="Nikita")  # Use contact's name
target_wrp = target.wrapper_object()

msg_wrp = WhatsApp.child_window(title="Type a message ",
                                control_type="Group").wrapper_object()

target_wrp.click_input()
for x in range(100):
    WhatsApp.type_keys("Check out my spam bot..{}".format(x))
    WhatsApp.type_keys('{ENTER}')
예제 #5
0
"""
Example script for Calculator on Windows 10

Requirements:
  - Windows 10
  - pywinauto 0.6.1+

Win10 version of Calculator is very specific. Few different processes (!)
own different windows and controls, so the full hierarchy can be accessed
through Desktop object only.

Minimized Calculator is a process in a "Suspended" state.
But it can be restored with some trick for invisible main window.
"""

from pywinauto import Desktop, Application

app = Application(backend="uia").start('calc.exe')

dlg = Desktop(backend="uia").Calculator
dlg.type_keys('2*3=')
dlg.print_control_identifiers()

dlg.minimize()
Desktop(backend="uia").window(title='Calculator', visible_only=False).restore()
예제 #6
0
# Another pywinauto example

from pywinauto import Desktop, Application, keyboard
import time

# Open Calculator in Windows 10 and do some calculation
app = Application(backend='uia').start("calc.exe")
dlg = Desktop(backend="uia").Calculator
dlg.type_keys('3')
# Add some delay between each key stroke
time.sleep(1)
dlg.type_keys('/')
time.sleep(1)
dlg.type_keys('7')
time.sleep(1)
dlg.type_keys('=')
# Get calculation result
txt = dlg.Static3.texts()
# Get only the numeric value
txt = txt[0].split(' ')[2]

# Open Notepad from Windows 10
app2 = Application(backend='uia').start("notepad.exe")
time.sleep(1)
app2.Untitled.edit.type_keys(txt)
time.sleep(1)
# All {key code} are self explained
keyboard.SendKeys('{ENTER}')
app2.Untitled.edit.type_keys(
    u'Automate{SPACE}any{SPACE}Windows{SPACE}Application')
keyboard.SendKeys('{ENTER}')
예제 #7
0
#!usr/bin/python
# -*- coding: utf-8 -*-
from subprocess import Popen
from pywinauto import Desktop
import time
Popen('D:\Program Files\DuoLaBao\unins000.exe', shell=True)
time.sleep(2)
dlg = Desktop(backend="win32").window(title=u"哆啦宝 反安装")

# 界面一 您确定完全删除 哆啦宝 和相关组件吗?
# 获取路径输入框
dlg.type_keys("%Y")

# 界面二 哆啦宝 被成功地从您的电脑中删除。
# 发送快捷键 下一步
time.sleep(2)
dlgv = Desktop(backend="win32").window(title=u"哆啦宝 反安装")
buttonOk = u"确定"
dlgv[buttonOk].click()





예제 #8
0
from pywinauto import Desktop, Application

app = Application(backend="uia").start('calc.exe')

dlg = Desktop(backend="uia").Calculator
dlg.type_keys('23*3=')
dlg.print_control_identifiers()

dlg.minimize()
Desktop(backend="uia").window(title='Calculator', visible_only=False).restore()
예제 #9
0
파일: winauto.py 프로젝트: ok0755/win_auto
    backend='win32'
)['qadui: CCJX Domain CCJX [RMB] > CCJX 捷和电机(江西)有限公司 (2) - QAD Enterprise Applications']
sleep(2)
ui = newdlg2.window(title='物料用途表查询',
                    class_name='WindowsForms10.Window.8.app.0.83a9e6_r15_ad1')
newdlg2.wait('visible', timeout=10)
newdlg2.maximize()
ui.type_keys(var)
ui.type_keys('{ENTER 2}')
sleep(2)
newdlg2.click(button='left',
              pressed='',
              coords=(500, 500),
              double=False,
              absolute=False)
newdlg2.type_keys('^a')
newdlg2.type_keys('^c')
qad3 = Desktop(
    backend='win32'
)['qadui: CCJX Domain CCJX [RMB] > CCJX 捷和电机(江西)有限公司 (3) - QAD Enterprise Applications']
#print(qad3.print_control_identifiers())
"""
newdlg['Edit'].type_keys('{ENTER 1}')
sleep(0.5)
newdlg.type_keys(var)
sleep(0.2)
newdlg.type_keys('{ENTER 1}')
sleep(0.2)
newdlg.type_keys('{ENTER 1}',with_spaces=True, set_foreground=True)
sleep(0.2)
newdlg.type_keys('^A')
예제 #10
0
    def OnSend(self, event):
        try:
            self.m_send.Disable()
            if not hyhr_key.Hyhr_key.IsKeyValid(hyhr_key.KEY.Key):
                logger.error(hyhr_def.HYHR_KEY_ERROR)
                wx.MessageBox(hyhr_def.HYHR_KEY_ERROR)
                return
            else:
                logger.info(hyhr_def.HYHR_KEY_VALID)
            #check key exists
            # if not os.path.isfile(key):
            # 	wx.MessageBox('认证码不存在,请先到菜单文件--认证中输入认证码')
            # 	logger.error('认证码不存在')
            # 	return
            # else:
            # 	with open(key, 'r', encoding='utf-8') as k:
            # 		data = k.read()
            # 		key_date = datetime.datetime.strptime(hyhr_encrypt.Decrypt(data.encode()),hyhr_def.HYHR_KEY_FORMAT)
            # 		if hyhr_encrypt.Global_Cur_Date:
            # 			cur_date = datetime.datetime.strptime(hyhr_encrypt.Global_Cur_Date,hyhr_def.HYHR_KEY_FORMAT)
            # 		else:
            # 			cur_date = datetime.datetime.strptime(hyhr_encrypt.GetCurDate(),hyhr_def.HYHR_KEY_FORMAT)
            # 		if cur_date > key_date:
            # 			wx.MessageBox(hyhr_def.HYHR_KEY_EXPIRED)
            # 			logger.error(hyhr_def.HYHR_KEY_EXPIRED)
            # 			return
            # 		else:
            # 			logger.info('认证码有效!')
            self.msg = self.m_richText3.GetValue()
            if len(self.names) == 0 or (len(self.msg) == 0
                                        and len(self.file) == 0):
                wx.MessageBox(hyhr_def.HYHR_NAME_MSG_FILE_EMPTY)
                logger.error(hyhr_def.HYHR_NAME_MSG_FILE_EMPTY)
                return

            if not os.path.isfile(wechat):
                wx.MessageBox(hyhr_def.HYHR_WECHAT_NOT_INSTALLED)
                logger.error(hyhr_def.HYHR_WECHAT_NOT_INSTALLED)
                return
            app = Application(backend='uia').start(wechat)
            try:
                dlg = Desktop(backend='uia').window(
                    class_name=wechat_class_name)
                dlg.set_focus()
            except Exception as ex:
                wx.MessageBox(hyhr_def.HYHR_WECHAT_NOT_STARTED)
                logger.error(f'{hyhr_def.HYHR_WECHAT_NOT_STARTED} {ex}')
                return
            wrapper = dlg.wrapper_object()
            wrapper.click_input(coords=(searchbox_x, searchbox_y))

            counter = 0
            for info in self.names:
                name = None
                data = []
                vals = []
                validData = True
                info = info.strip()
                if not len(info):
                    continue
                vals = re.split(r'\s+', info)
                length = len(vals)
                if length >= 1:
                    name = vals[0]
                else:
                    logger.warning('异常数据,忽略.')
                    counter += 1
                    continue

                if len(self.msg):
                    for i in range(1, length):
                        try:
                            fee = float(vals[i])
                            data.append(fee)
                        except Exception as ex:
                            logger.warning('异常数值:{}!暂不发送,请核对后重试!'.format(info))
                            validData = False
                            break

                if not validData:
                    counter += 1
                    continue

                try:
                    wrapper.click_input(coords=(searchbox_x, searchbox_y))
                    wrapper.type_keys(name)
                    time.sleep(1.5)
                    wrapper.click_input(coords=(searchbox_x, searchResult_y))
                    noFoundDlg = Desktop(backend='uia').window(
                        class_name=wechat_notFound_class_name)
                    #time.sleep(0.5)
                    if noFoundDlg.exists(timeout=2):
                        noFoundDlg.close()
                        logger.warning('{} 不存在,请手工确认'.format(name))
                        time.sleep(1)
                        counter += 1
                        continue

                    if len(self.msg):
                        if len(data) == 0:
                            dlg.type_keys(self.msg.replace('{', '').replace(
                                '}', ''),
                                          with_spaces=True)
                        else:
                            if '{}' in self.msg:
                                if self.msg.count('{}') == len(data):
                                    dlg.type_keys(self.msg.format(*data),
                                                  with_spaces=True)
                                else:
                                    logger.warning(
                                        f'{name} 数据数目和消息格式不匹配,忽略该条记录!')
                                    counter += 1
                                    continue
                            else:
                                dlg.type_keys(self.msg, with_spaces=True)
                        dlg.type_keys('%{s}')
                        logger.info('发送消息给{}成功'.format(name))

                    if len(self.file):
                        #try to send file
                        #for f in os.listdir(self.file):
                        wrapper.click_input(coords=(sendfile_x, sendfile_y))
                        #pywinauto.keyboard.send_keys(self.file)
                        pywinauto.keyboard.send_keys(self.file)
                        pywinauto.keyboard.send_keys('{ENTER 1}')
                        dlg.type_keys('%{s}')
                        logger.info('发送文件{}给{}成功'.format(self.file, name))

                    self.m_namesList.SetItem(counter, 1, '✔')
                    self.m_namesList.SetItemTextColour(counter, wx.GREEN)
                    self.m_namesList.itemDataMap[counter] = (name, '✔')
                    counter += 1

                except Exception as ex:
                    #wx.MessageBox('发送错误!{}.'.format(ex))
                    logger.warning(f'{hyhr_def.HYHR_SEND_ERROR}{ex}.')
                    counter += 1
        except Exception as ex:
            wx.MessageBox(f'{hyhr_def.HYHR_SEND_ERROR}{ex}.')
            logger.error(f'{hyhr_def.HYHR_SEND_ERROR} {ex}.')
        finally:
            self.m_send.Enable()
        event.Skip()
예제 #11
0
파일: check.py 프로젝트: nkpc14/ARYA
class AryaAI:
    """ Pywin @params  """
    MyApplicationList = {
        'sublime':
        'C:\\Program Files\\Sublime Text 3\\sublime_text.exe',
        'notepad':
        'notepad.exe',
        'paint':
        'mspaint.exe',
        'chrome':
        'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
    }
    dlg = None
    app = None
    pxwindowclass = None
    menu_item = None

    def __init__(self):
        self.voiceModel = ""
        """ Starting Speech Recognisation  """

    def show():

        # Open "Control Panel"
        Application().start('control.exe')
        app = Application(backend='uia').connect(path='explorer.exe',
                                                 title='Control Panel')

        # Go to "Programs"
        app.window(title='Control Panel').ProgramsHyperlink.invoke()
        app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0)

        # Go to "Installed Updates"
        app.window(title='Programs').child_window(
            title='View installed updates', control_type='Hyperlink').invoke()
        app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0)

        list_box = app.InstalledUpdates.FolderViewListBox

        # list all updates
        items = list_box.descendants(control_type='ListItem')
        all_updates = [item.window_text() for item in items]
        print('\nAll updates ({}):\n'.format(len(all_updates)))
        print(all_updates)

        # list updates from "Microsoft Windows" group only
        windows_group_box = list_box.child_window(
            title_re='^Microsoft Windows.*', control_type='Group')
        windows_items = windows_group_box.descendants(control_type='ListItem')
        windows_updates = [item.window_text() for item in windows_items]
        print('\nWindows updates only ({}):\n'.format(len(windows_updates)))
        print(windows_updates)

    def aryaSTT(self):
        """
        # obtain audio from the microphone
        main()
        self.voiceModel = AryaSpeechModule.voiceModelData
        print("Arya : " + self.voiceModel)
        """
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say something!")
            audio = r.listen(source)
        # recognize speech using ARYA Speech Recognition
        GOOGLE_CLOUD_SPEECH_CREDENTIALS = os.environ.get(
            'GOOGLE_APPLICATION_CREDENTIALS')
        try:
            print(
                "Google Cloud Speech recognition for \"numero\" with different sets of preferred phrases:"
            )
            print(
                r.recognize_google_cloud(
                    audio,
                    credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS,
                    preferred_phrases=["noomarow"]))
            print(
                r.recognize_google_cloud(
                    audio,
                    credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS,
                    preferred_phrases=["newmarrow"]))
        except sr.UnknownValueError:
            print("Google Cloud Speech could not understand audio")
        except sr.RequestError as e:
            print(
                "Could not request results from Google Cloud Speech service; {0}"
                .format(e))

        try:
            self.voiceModel = r.recognize_google(audio)
            print("ARYA thinks you said " + self.voiceModel)
        except sr.UnknownValueError:
            print("ARYA  could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from ARYA service; {0}".format(e))
        self.voiceModel = self.voiceModel.lower()

    def startSublime(self):
        self.app = Application().Start(
            cmd_line=u'"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"')
        self.app = Application().Connect(
            title=u'untitled (demo) - Sublime Text (UNREGISTERED)',
            class_name='PX_WINDOW_CLASS')
        self.pxwindowclass = app.PX_WINDOW_CLASS
        self.pxwindowclass.Wait('ready')
        menu_item2 = self.pxwindowclass.MenuItem(u'&File->&New File\tCtrl+N')
        menu_item2.ClickInput()

    def startChrome(self):
        app = Application().Start(
            cmd_line=
            u'"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" -- "http:\\www.msftconnecttest.com\\redirect"'
        )
        chromewidgetwin = app.Chrome_WidgetWin_1
        chromewidgetwin.Wait('ready')

    def startPaint(self):
        self.app = Application(backend='uia').start(r'mspaint.exe')
        self.dlg = self.app.window(title_re='.* - Paint')

    def startNotepad(self):
        app = Application().Start(
            cmd_line=u'"C:\\WINDOWS\\system32\\notepad.exe" ')
        self.notepad = app.Notepad
        self.notepad.Wait('ready')

    def openFile(self, param):
        if (param == "sublime"):
            self.menu_item = self.pxwindowclass.MenuItem(u'&File')
            self.menu_item.ClickInput()
        elif (param == "notepad"):
            self.menu_item = self.notepad.MenuItem(u'&File')
            self.menu_item.ClickInput()
        elif (param == "paint"):
            self.dlg.File_tab.click()
            self.dlg.child_window(title='Open',
                                  control_type='MenuItem',
                                  found_index=0).invoke()
        else:
            pass

    def openNewFile(self, param):
        if (param == "sublime"):
            self.menu_item2 = self.pxwindowclass.MenuItem(
                u'&File->&New\tCtrl+N')
            self.menu_item2.ClickInput()
        elif (param == "notepad"):
            self.menu_item = self.notepad.MenuItem(u'&File->&New File\tCtrl+N')
            self.menu_item.ClickInput()

        elif (param == "paint"):
            self.dlg.File_tab.click()
            self.dlg.child_window(title='New',
                                  control_type='MenuItem',
                                  found_index=0).invoke()

        elif (param == "chrome"):
            pass
        else:
            pass

    def exitProgramm(self):
        self.app = Application().Connect(
            title=u'untitled (demo) - Sublime Text (UNREGISTERED)',
            class_name='PX_WINDOW_CLASS')
        self.menu_item2 = self.pxwindowclass.MenuItem(u'&File->&Exit')
        self.menu_item2.ClickInput()

    def typeSomething(self, param, message):

        if (param == "sublime"):
            self.pxwindowclass.type_keys(message, with_spaces=True)
        elif (param == "notepad"):
            self.notepad.type_keys("Hello welcome to ARYA!", with_spaces=True)
        else:
            pass

    def saveAs(self, param):
        if (param == "sublime"):
            self.menu_item = self.pxwindowclass.MenuItem(
                u'&File->Save &As\u2026\tCtrl+Shift+S')
            self.menu_item.ClickInput()
            SendKeys('{ENTER 2}')
        elif (param == "notepad"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
            self.app.SaveAs.EncodingComboBox.select("UTF-8")
            self.app.SaveAs.edit1.set_edit_text("Example-utf8.txt")
            self.app.SaveAs.Save.close_click()
        elif (param == "paint"):
            self.dlg = self.app.window(title_re='.* - Paint')
            self.dlg.File_tab.click()
            self.dlg.SaveAsGroup.child_window(title="Save as",
                                              found_index=1).invoke()
        elif (param == "chrome"):
            pass
        else:
            pass

    def selectAll(self, param):
        if (param == "sublime"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            menu_item2 = self.app.notepad.menu_select(
                "Edit->Select All\tCtrl+A")
            menu_item2.ClickInput()

    def copy(self, param):
        if (param == "sublime"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            menu_item2 = self.app.notepad.menu_select("Edit->Copy\tCtrl+C")
            menu_item2.ClickInput()

    def paste(self, param):
        if (param == "sublime"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            menu_item2 = self.app.notepad.menu_select("Edit->Paste\tCtrl+V")
            menu_item2.ClickInput()

    def exitApp(self, param):
        if param == "sublime":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->Exit")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->Exit")

    def aryaVoiceModule(self, speech):
        engine = pyttsx3.init()
        engine.say(speech)
        engine.runAndWait()

    def openPaintMenuItem(self, param):
        if param == "new":
            self.dlg.child_window(title='New',
                                  control_type='MenuItem',
                                  found_index=0).invoke()
        elif param == "open":
            self.dlg.child_window(title='Open',
                                  control_type='MenuItem',
                                  found_index=0).invoke()
        elif param == "exit":
            self.dlg.child_window(title='Exit',
                                  control_type='MenuItem',
                                  found_index=0).invoke()

    def fileName(self, FileName):
        file_name_edit = self.dlg.Open.child_window(title="File name:",
                                                    control_type="Edit")
        file_name_edit.set_text(FileName + '.jpg')
        self.dlg.Open.child_window(title="Open",
                                   auto_id="1",
                                   control_type="Button").click()

    def resizePaint(self):
        self.dlg = self.app.window(title_re='.* - Paint')
        self.dlg.ResizeButton.click()
        self.dlg.ResizeAndSkew.Pixels.select()
        if self.dlg.ResizeAndSkew.Maintain_aspect_ratio.get_toggle_state(
        ) != 1:
            self.dlg.ResizeAndSkew.Maintain_aspect_ratio.toggle()
        self.dlg.ResizeAndSkew.HorizontalEdit1.set_text('100')
        self.dlg.ResizeAndSkew.OK.click()

    def saveImageType(self, param):
        self.dlg = self.app.window(title_re='.* - Paint')
        if param == "png":
            self.dlg.child_window(title='PNG picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()
        elif param == "jpg":
            self.dlg.child_window(title='JPEG picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()
        elif param == "bmp":
            self.dlg.child_window(title='BMP picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()
        elif param == "gif":
            self.dlg.child_window(title='GIF picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()

    def printPaint(self):
        self.dlg.SaveAsGroup.child_window(title="Print",
                                          found_index=1).invoke()
        self.dlg.child_window(title='Print', found_index=0).invoke()

    def close(self):
        self.dlg = self.app.window(title_re='.* - Paint')
        self.dlg.close()

    def calDemo(self):
        pass

    def startCal(self):
        self.app = self.Application(backend="uia").start('calc.exe')
        self.dlg = Desktop(backend="uia").Calculator
        self.dlg.type_keys('2*3=')
        self.dlg.print_control_identifiers()

    def exitNotepad(self):
        self.app = Application().connect(title_re=".*Notepad",
                                         class_name="Notepad")
        self.menu_item = self.notepad.MenuItem(u'&File')
        self.menu_item.ClickInput()
예제 #12
0
class AryaAI:
    """ Pywin @params  """
    MyApplicationList = {
        'sublime':
        'C:\\Program Files\\Sublime Text 3\\sublime_text.exe',
        'notepad':
        'notepad.exe',
        'paint':
        'mspaint.exe',
        'chrome':
        'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
    }
    dlg = None
    app = None
    pxwindowclass = None
    menu_item = None

    def __init__(self):
        self.voiceModel = ""
        """ Starting Speech Recognisation  """

    def show():

        # Open "Control Panel"
        Application().start('control.exe')
        app = Application(backend='uia').connect(path='explorer.exe',
                                                 title='Control Panel')

        # Go to "Programs"
        app.window(title='Control Panel').ProgramsHyperlink.invoke()
        app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0)

        # Go to "Installed Updates"
        app.window(title='Programs').child_window(
            title='View installed updates', control_type='Hyperlink').invoke()
        app.wait_cpu_usage_lower(threshold=0.5, timeout=30, usage_interval=1.0)

        list_box = app.InstalledUpdates.FolderViewListBox

        # list all updates
        items = list_box.descendants(control_type='ListItem')
        all_updates = [item.window_text() for item in items]
        print('\nAll updates ({}):\n'.format(len(all_updates)))
        print(all_updates)

        # list updates from "Microsoft Windows" group only
        windows_group_box = list_box.child_window(
            title_re='^Microsoft Windows.*', control_type='Group')
        windows_items = windows_group_box.descendants(control_type='ListItem')
        windows_updates = [item.window_text() for item in windows_items]
        print('\nWindows updates only ({}):\n'.format(len(windows_updates)))
        print(windows_updates)

    def aryaSTT(self):
        AryaMicToAudio.main()
        self.voiceModel = AryaAudToRecognise.convertToText()
        self.voiceModel = self.voiceModel.lower()

    def startSublime(self):
        self.app = Application().Start(
            cmd_line=u'"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"')
        self.app = Application().Connect(
            title=u'untitled (demo) - Sublime Text (UNREGISTERED)',
            class_name='PX_WINDOW_CLASS')
        self.pxwindowclass = app.PX_WINDOW_CLASS
        self.pxwindowclass.Wait('ready')
        menu_item2 = self.pxwindowclass.MenuItem(u'&File->&New File\tCtrl+N')
        menu_item2.ClickInput()

    def startChrome(self):
        app = Application().Start(
            cmd_line=
            u'"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" -- "http:\\www.msftconnecttest.com\\redirect"'
        )
        chromewidgetwin = app.Chrome_WidgetWin_1
        chromewidgetwin.Wait('ready')

    def startPaint(self):
        self.app = Application(backend='uia').start(r'mspaint.exe')
        self.dlg = self.app.window(title_re='.* - Paint')

    def startNotepad(self):
        app = Application().Start(
            cmd_line=u'"C:\\WINDOWS\\system32\\notepad.exe" ')
        self.notepad = app.Notepad
        self.notepad.Wait('ready')

    def openFile(self, param):
        if (param == "sublime"):
            self.menu_item = self.pxwindowclass.MenuItem(u'&File')
            self.menu_item.ClickInput()
        elif (param == "notepad"):
            self.menu_item = self.notepad.MenuItem(u'&File')
            self.menu_item.ClickInput()
        elif (param == "paint"):
            self.dlg.File_tab.click()
            self.dlg.child_window(title='Open',
                                  control_type='MenuItem',
                                  found_index=0).invoke()
        else:
            pass

    def openNewFile(self, param):
        if (param == "sublime"):
            self.menu_item2 = self.pxwindowclass.MenuItem(
                u'&File->&New\tCtrl+N')
            self.menu_item2.ClickInput()
        elif (param == "notepad"):
            self.menu_item = self.notepad.MenuItem(u'&File->&New File\tCtrl+N')
            self.menu_item.ClickInput()

        elif (param == "paint"):
            self.dlg.File_tab.click()
            self.dlg.child_window(title='New',
                                  control_type='MenuItem',
                                  found_index=0).invoke()

        elif (param == "chrome"):
            pass
        else:
            pass

    def exitProgramm(self):
        self.app = Application().Connect(
            title=u'untitled (demo) - Sublime Text (UNREGISTERED)',
            class_name='PX_WINDOW_CLASS')
        self.menu_item2 = self.pxwindowclass.MenuItem(u'&File->&Exit')
        self.menu_item2.ClickInput()

    def typeSomething(self, param, message):

        if (param == "sublime"):
            self.pxwindowclass.type_keys(message, with_spaces=True)
        elif (param == "notepad"):
            self.notepad.type_keys(message, with_spaces=True)
        else:
            pass

    def saveAs(self, param):
        if (param == "sublime"):
            self.menu_item = self.pxwindowclass.MenuItem(
                u'&File->Save &As\u2026\tCtrl+Shift+S')
            self.menu_item.ClickInput()
            SendKeys('{ENTER 2}')
        elif (param == "notepad"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
            self.app.SaveAs.EncodingComboBox.select("UTF-8")
            self.app.SaveAs.edit1.set_edit_text("Example-utf8.txt")
            self.app.SaveAs.Save.close_click()
        elif (param == "paint"):
            self.dlg = self.app.window(title_re='.* - Paint')
            self.dlg.File_tab.click()
            self.dlg.SaveAsGroup.child_window(title="Save as",
                                              found_index=1).invoke()
        elif (param == "chrome"):
            pass
        else:
            pass

    def selectAll(self, param):
        if (param == "sublime"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            menu_item2 = self.app.notepad.menu_select(
                "Edit->Select All\tCtrl+A")
            menu_item2.ClickInput()

    def copy(self, param):
        if (param == "sublime"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            menu_item2 = self.app.notepad.menu_select("Edit->Copy\tCtrl+C")
            menu_item2.ClickInput()

    def paste(self, param):
        if (param == "sublime"):
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->SaveAs")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            menu_item2 = self.app.notepad.menu_select("Edit->Paste\tCtrl+V")
            menu_item2.ClickInput()

    def exitApp(self, param):
        if param == "sublime":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->Exit")
        elif param == "notepad":
            self.app = Application().connect(title_re=".*Notepad",
                                             class_name="Notepad")
            self.app.notepad.menu_select("File->Exit")

    def aryaVoiceModule(self, speech):
        engine = pyttsx3.init()
        engine.say(speech)
        engine.runAndWait()

    def openPaintMenuItem(self, param):
        if param == "new":
            self.dlg.child_window(title='New',
                                  control_type='MenuItem',
                                  found_index=0).invoke()
        elif param == "open":
            self.dlg.child_window(title='Open',
                                  control_type='MenuItem',
                                  found_index=0).invoke()
        elif param == "exit":
            self.dlg.child_window(title='Exit',
                                  control_type='MenuItem',
                                  found_index=0).invoke()

    def fileName(self, FileName):
        file_name_edit = self.dlg.Open.child_window(title="File name:",
                                                    control_type="Edit")
        file_name_edit.set_text(FileName + '.jpg')
        self.dlg.Open.child_window(title="Open",
                                   auto_id="1",
                                   control_type="Button").click()

    def resizePaint(self):
        self.dlg = self.app.window(title_re='.* - Paint')
        self.dlg.ResizeButton.click()
        self.dlg.ResizeAndSkew.Pixels.select()
        if self.dlg.ResizeAndSkew.Maintain_aspect_ratio.get_toggle_state(
        ) != 1:
            self.dlg.ResizeAndSkew.Maintain_aspect_ratio.toggle()
        self.dlg.ResizeAndSkew.HorizontalEdit1.set_text('100')
        self.dlg.ResizeAndSkew.OK.click()

    def saveImageType(self, param):
        self.dlg = self.app.window(title_re='.* - Paint')
        if param == "png":
            self.dlg.child_window(title='PNG picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()
        elif param == "jpg":
            self.dlg.child_window(title='JPEG picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()
        elif param == "bmp":
            self.dlg.child_window(title='BMP picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()
        elif param == "gif":
            self.dlg.child_window(title='GIF picture', found_index=0).invoke()
            self.dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
            self.dlg.SaveAs.Save.click()
            if self.dlg.ConfirmSaveAs.exists():
                self.dlg.ConfirmSaveAs.Yes.click()
            #self.dlg.close()

    def printPaint(self):
        self.dlg.SaveAsGroup.child_window(title="Print",
                                          found_index=1).invoke()
        self.dlg.child_window(title='Print', found_index=0).invoke()

    def close(self):
        self.dlg = self.app.window(title_re='.* - Paint')
        self.dlg.close()

    def calDemo(self):
        app = Application(backend="uia").start('calc.exe')
        dlg = Desktop(backend="uia").Calculator
        dlg.type_keys('2*3=')
        dlg.print_control_identifiers()
        dlg.minimize()
        Desktop(backend="uia").window(title='Calculator',
                                      visible_only=False).restore()

    def startCal(self):
        self.app = self.Application(backend="uia").start('calc.exe')
        self.dlg = Desktop(backend="uia").Calculator
        self.dlg.type_keys('2*3=')
        self.dlg.print_control_identifiers()

    def exitNotepad(self):
        self.app = Application().connect(title_re=".*Notepad",
                                         class_name="Notepad")
        self.menu_item = self.notepad.MenuItem(u'&File')
        self.menu_item.ClickInput()

    def msPaintDemo(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("--log",
                            help="enable logging",
                            type=str,
                            required=False)
        args = parser.parse_args()
        actionlogger.enable()
        logger = logging.getLogger('pywinauto')
        if args.log:
            logger.handlers[0] = logging.FileHandler(args.log)

        app = Application(backend='uia').start(r'mspaint.exe')
        dlg = app.window(title_re='.* - Paint')
        # File->Open menu selection
        dlg.File_tab.click()
        dlg.child_window(title='Open', control_type='MenuItem',
                         found_index=0).invoke()

        # handle Open dialog
        file_name_edit = dlg.Open.child_window(title="File name:",
                                               control_type="Edit")
        file_name_edit.set_text('image.jpg')
        dlg.Open.child_window(title="Open", auto_id="1",
                              control_type="Button").click()
        dlg.ResizeButton.click()
        dlg.ResizeAndSkew.Pixels.select()
        if dlg.ResizeAndSkew.Maintain_aspect_ratio.get_toggle_state() != 1:
            dlg.ResizeAndSkew.Maintain_aspect_ratio.toggle()
        dlg.ResizeAndSkew.HorizontalEdit1.set_text('100')
        dlg.ResizeAndSkew.OK.click()
        # Select menu "File->Save as->PNG picture"
        dlg.File_tab.click()
        dlg.SaveAsGroup.child_window(title="Save as", found_index=1).invoke()
        dlg.child_window(title='PNG picture', found_index=0).invoke()
        # Type output file name and save
        dlg.SaveAs.File_name_ComboBox.Edit.set_text('image.png')
        dlg.SaveAs.Save.click()
        if dlg.ConfirmSaveAs.exists():
            dlg.ConfirmSaveAs.Yes.click()
        # Close application
        dlg.close()
예제 #13
0
def Install():
    Popen(r'D:\Client\DuoLaBao\Setup-DLB-1.4.12.1.exe', shell=True)
    time.sleep(1)
    dlg = Desktop(backend="win32").window(title=u"安装 - 哆啦宝")

    # 界面一 您将把哆啦宝安装在哪里?
    # 界面一 您将把哆啦宝安装在哪里?
    time.sleep(1)
    # 获取路径输入框
    dlg.window(class_name="TEdit")
    edit = dlg['TEdit']
    # 输入路径
    edit.set_text(r'D:\Program Files\DuoLaBao')
    # 发送快捷键 下一步
    dlg.type_keys("%N")

    # 文件夹已经存在
    # 文件夹已经存在
    time.sleep(2)
    exeits = Desktop(backend="win32").window(title=u"文件夹已经存在")
    #判断窗体是否存在
    if exeits.exists():
        exeits.type_keys("%Y")

    # 界面二 您想选择哪个附加任务?
    # 界面二 您想选择哪个附加任务?
    # 发送快捷键 下一步
    time.sleep(2)
    dlg.type_keys("%N")

    # 界面三 安装程序开始在您的电脑中安装哆啦宝.
    # 界面三 安装程序开始在您的电脑中安装哆啦宝.
    time.sleep(2)
    dlg.type_keys("%I")

    #界面四 哆啦宝安装完成F
    #界面四 哆啦宝安装完成F
    time.sleep(2)
    dlgss = Desktop(backend="win32").window(title=u"安装 - 哆啦宝")
    dlgss.type_keys("%F")

    # 界面五 初始化激活提示
    # 界面五 初始化激活提示
    time.sleep(3)
    dlgcc = Desktop(backend="uia").window(title=u"初始化激活提示")
    # 获取窗体坐标
    idc = FromPostion.GetZuoBiao(dlgcc)
    # print idc
    # 获取屏幕大小
    screenWidth, screenHeight = pyautogui.size()
    # 获取当前鼠标位置
    currentMouseX, currentMouseY = pyautogui.position()

    # 激活对话框窗体操作
    # 激活对话框窗体操作
    def TuiChu():
        time.sleep(1)
        # 移动鼠标到指定位置
        pyautogui.moveTo(idc[0] + 130, idc[1] + 150)
        # 鼠标点击事件
        pyautogui.click()
        return

    TuiChu()
    return
예제 #14
0
파일: hycz_uia.py 프로젝트: woodhfut/hywx
                #dlg['3'].type_keys('{ENTER 1}')
                time.sleep(0.5)
                wrapper.click_input(coords=(width, height + 70))
                noFoundDlg = Desktop(backend='uia').window(
                    class_name='FTSMsgSearchWnd')
                #time.sleep(0.5)
                if noFoundDlg.exists(timeout=2):
                    noFoundDlg.close()
                    print('{} 不存在,请手工确认'.format(name))
                    time.sleep(1)
                    continue

                if bNeedSendMsg:
                    if len(data) == 0:
                        dlg.type_keys(message.replace('{',
                                                      '').replace('}', ''),
                                      with_spaces=True)
                    else:
                        if '{}' in message:
                            dlg.type_keys(message.format(*data),
                                          with_spaces=True)
                        else:
                            dlg.type_keys(message, with_spaces=True)
                    dlg.type_keys('%{s}')
                    print('发送消息给{}成功'.format(name))
                    stat[name].bMsg = True

                if bNeedSendFile:
                    #try to send file
                    for f in os.listdir(filesRootPath):
                        wrapper.click_input(coords=(width + 285, height + 525))
예제 #15
0
def install_maya():
    timings.Timings.slow()
    gdown.download(
        "https://drive.google.com/uc?export=download&id=1aegNaJNkPhueiSWu_JSOkDGwdDWsQZls",
        output=rf"{path}\software\Maya2020.4.7z")
    os.system('cls')
    os.system(
        rf"{path}\tools\7za.exe x {path}\software\Maya2020.4.7z -o{path}\software"
    )
    os.system('cls')
    print('Installing Autodesk Maya 2020.....')
    os.system('".\\software\\Autodesk Maya 2020.4\\Setup.exe" --silent')
    Application(backend='uia').start(
        "C:\\Program Files\\Autodesk\\Maya2020\\bin\\maya.exe")
    time.sleep(10)
    maya = Desktop(backend='uia').window(title="IE WebBrowser")
    maya.set_focus()
    maya.Hyperlink2.click_input()
    maya = Desktop(backend='uia').window(title="Autodesk Licensing")
    maya.set_focus()
    maya['I Agree Enter'].click_input()
    maya['Activate Enter'].click_input()
    maya = Desktop(backend='uia').window(
        title="Autodesk Licensing - Activation Options")
    maya.set_focus()
    maya.Edit1.click_input()
    maya.type_keys("666")
    maya.Edit2.click_input()
    maya.type_keys("69696969")
    maya.Next.click_input()
    maya = Desktop(backend='uia').window(
        title="Autodesk Licensing - Activating")
    maya.set_focus()
    time.sleep(5)
    maya.Static12.click_input()
    maya['Yes Enter'].click_input()
    maya = Desktop(backend='uia').window(title="Autodesk Licensing")
    maya.set_focus()
    maya['Activate Enter'].click_input()
    maya = Desktop(backend='uia').window(
        title="Autodesk Licensing - Activation Options")
    maya.set_focus()
    maya.Edit1.click_input()
    maya.type_keys("666")
    maya.Edit2.click_input()
    maya.type_keys("69696969")
    maya.Next.click_input()
    input("Please provide request code manually: ")
    Application(backend="uia").start(cmd_line='.\\software\\xf-adesk20_v2.exe')
    xforce = Desktop(backend='uia').window(
        title="Autodesk 2020 live Keymaker - X-FORCE")
    xforce.set_focus()
    xforce['Request :Edit'].click_input(button="right")
    dsk.Context.SelectAll.click_input()
    keyboard.send_keys("{VK_DELETE}")
    keyboard.send_keys("^v")
    xforce.CButton.click_input()
    xforce.OKButton.click_input()
    xforce.GButton.click_input()
    xforce['Activation :Edit'].click_input(button="right")
    dsk.Context.SelectAll.click_input()
    keyboard.send_keys("^c")
    os.system("TASKKILL /F /IM xf-adesk20_v2.exe")
    maya.set_focus()
    maya['I have an activation code from Autodesk'].click_input()
    maya.Edit1.click_input()
    keyboard.send_keys("^v")
    maya.Next.click_input()
    maya = Desktop(backend='uia').window(
        title="Autodesk Licensing - Activation Complete")
    maya.FinishButton.click_input()
    time.sleep(3)
    os.system("TASKKILL /F /IM maya.exe")
    os.system('cls')
예제 #16
0
파일: pywinauto.py 프로젝트: nkpc14/ARYA
# app.UntitledNotepad.type_keys("%FX")


from subprocess import Popen
from pywinauto import Desktop

Popen('calc.exe', shell=True)
dlg = Desktop(backend="uia").Calculator
dlg.wait('visible')

# can be multi-level
app.window(title_re='.* - Notepad$').window(class_name='Edit')

# can combine criteria
dlg = Desktop(backend="uia").Calculator
dlg.window(auto_id='num8Button', control_type='Button')





from pywinauto import Desktop, Application

app = Application(backend="uia").start('calc.exe')

dlg = Desktop(backend="uia").Calculator
dlg.type_keys('2*3=+5+9=')
dlg.print_control_identifiers()

dlg.minimize()
Desktop(backend="uia").window(title='Calculator', visible_only=False).restore()