Example #1
0
    def _launch_invisible(self):
        '''launches phantom js invisible SHOULD ONLY BE USED ONCE'''
        try:
            DATA_PATH = r"drivers\phantomjs.exe"
            #os.environ["webdriver.chrome.driver"] = DATA_PATH
            #self.driver = webdriver.PhantomJS(DATA_PATH)

            user_agent = (
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
                "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
            )
            
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            dcap["phantomjs.page.settings.userAgent"] = user_agent

            self.driver = webdriver.PhantomJS(DATA_PATH, desired_capabilities=dcap)
            
            window_h = findwindows.find_windows(title_re = r"*[^^]phantomjs\.exe")
            while len(window_h) == 0:
                window_h = findwindows.find_windows(title_re = r'*[^^]phantomjs\.exe')

            win32gui.ShowWindow(window_h[0], False)
            #launches PhantomJS then makes window invisible
            return True
        except:
            return False
Example #2
0
    def testConnect_windowspec(self):
        "Test that connect_() works with a windowspec"
        app1 = Application()
        app1.start(_notepad_exe())
        #unused var: handle = app1.UntitledNotepad.handle

        app_conn = Application()
        try:
            app_conn.connect(title="Untitled - Notepad")
        except findwindows.WindowAmbiguousError:
            wins = findwindows.find_windows(active_only=True,
                                            title="Untitled - Notepad")
            app_conn.connect(handle=wins[0])
        except findwindows.WindowNotFoundError:
            WaitUntil(
                30, 0.5, lambda: len(
                    findwindows.find_windows(active_only=True,
                                             title="Untitled - Notepad")) > 0)
            wins = findwindows.find_windows(active_only=True,
                                            title="Untitled - Notepad")
            app_conn.connect(handle=wins[0])

        self.assertEqual(app1.process, app_conn.process)

        app_conn.UntitledNotepad.MenuSelect('File->Exit')
Example #3
0
def login(data):
    #5回ログイン失敗したら処理を中止する
    login_count = 0
    while True:
        if login_count >= 5:
            logOut()
            raise Exception("login failed")

        try:
            #login failed窓口が現すと中止する
            handles = findwindows.find_windows(title_re='Verification Failed', class_name="#32770")
            if len(handles) > 0:
                raise Exception("Incorrect username or password")

            handles = findwindows.find_windows(title_re='iTunes', class_name="#32770")
            if len(handles) > 0:
                #Edit user,Edit2 password
                login_form = APP.window_(title_re='iTunes',  class_name="#32770")
                login_form['Edit'].SetText(data['apple_id'])
                login_form['Edit2'].SetText(data['password'])
                login_form['Edit'].SetText(data['apple_id'])
                login_form['Edit2'].SetText(data['password'])
                login_form['Button'].Click()
                keyEvent(win32con.VK_RETURN)
                return True
            else:
                time.sleep(2)
                login_count += 1
        except:
            login_count += 1
            time.sleep(2)
Example #4
0
    def _launch_invisible(self):
        '''launches phantom js invisible SHOULD ONLY BE USED ONCE'''
        try:
            DATA_PATH = r"drivers\phantomjs.exe"
            #os.environ["webdriver.chrome.driver"] = DATA_PATH
            #self.driver = webdriver.PhantomJS(DATA_PATH)

            user_agent = (
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
                "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
            )

            dcap = dict(DesiredCapabilities.PHANTOMJS)
            dcap["phantomjs.page.settings.userAgent"] = user_agent

            self.driver = webdriver.PhantomJS(DATA_PATH,
                                              desired_capabilities=dcap)

            window_h = findwindows.find_windows(
                title_re=r"*[^^]phantomjs\.exe")
            while len(window_h) == 0:
                window_h = findwindows.find_windows(
                    title_re=r'*[^^]phantomjs\.exe')

            win32gui.ShowWindow(window_h[0], False)
            #launches PhantomJS then makes window invisible
            return True
        except:
            return False
Example #5
0
 def testWaitCPUUsageLower(self):
     if is_x64_Python() != is_x64_OS():
         return None
     
     app = Application().Start(r'explorer.exe')
     WaitUntil(30, 0.5, lambda: len(findwindows.find_windows(active_only=True, class_name='CabinetWClass')) > 0)
     handle = findwindows.find_windows(active_only=True, class_name='CabinetWClass')[-1]
     window = WindowSpecification({'handle': handle, })
     explorer = Application().Connect(process=window.ProcessID())
     
     try:
         window.AddressBandRoot.ClickInput(double=True)
         window.Edit.SetEditText(r'Control Panel\Programs\Programs and Features')
         window.TypeKeys(r'{ENTER 2}', set_foreground=False)
         WaitUntil(30, 0.5, lambda: len(findwindows.find_windows(active_only=True, title='Programs and Features', class_name='CabinetWClass')) > 0)
         explorer.WaitCPUUsageLower(threshold=2.5, timeout=40, usage_interval=2)
         installed_programs = window.FolderView.Texts()[1:]
         programs_list = ','.join(installed_programs)
         if ('Microsoft' not in programs_list) and ('Python' not in programs_list):
             HwndWrapper.ImageGrab.grab().save(r'explorer_screenshot.jpg')
         HwndWrapper.ActionLogger().log('\ninstalled_programs:\n')
         for prog in installed_programs:
             HwndWrapper.ActionLogger().log(prog)
         self.assertEqual(('Microsoft' in programs_list) or ('Python' in programs_list), True)
     finally:
         window.Close(2.0)
Example #6
0
def lookupWindow():
    idle = 0
    while (True):
        print("=================")
        try:
            wins = findwindows.find_windows()
            for win in wins:
                try:
                    title = handleprops.text(win)
                    print(title)
                    if title != None:
                        if "FTDI" in title:
                            print("--------------------find:" + title)
                            if treatadlink(win):
                                idle = 0
                        elif "设备驱动程序" in title:
                            print("、、、、、、、、、、、find:" + title)
                            if treatQudong(win):
                                idle = 0
                except UnicodeEncodeError as e:
                    print(e)
                    pass
            time.sleep(1)  #每秒检查一次
            idle += 1
            if idle > 5:  #连续五秒没有查找到窗口则退出
                break
        except:
            traceback.print_exc()
            a = input("except")
Example #7
0
    def __init__(self, program_title=None, program_exe=None, ImgPath='img'):
        """
        :param program_title: title name of a window (partial is OK)
        :param program_exe: path to a program
        """
        if program_exe is not None:
            app = pywinauto.Application().start(
                program_exe)  # start the program

        elif program_title is not None:  # get the program id and connect to it
            handle = find_windows(title_re=program_title)[0]
            app = pywinauto.Application().connect(handle=handle)

        else:
            print("Please input program_title or program_exe")
            sys.exit()

        if not os.path.exists(ImgPath):
            os.makedirs(ImgPath)

        self.ImgPath = './' + ImgPath + '/'

        self.dlg = app.window(
        )  # get the window of the program (assume there is only one)
        self.locs = []  # list of locations to click; order matters
        self.ratio = 1  #ratio to enlarge/shrink icon
Example #8
0
 def __init__(self, strCharacter):
     self.app = pywinauto.application.Application()
     
     self.app.connect_(class_name="#32770", title = strCharacter)
     self.rxjh_dlg = self.app.Window_(class_name="#32770", title = strCharacter)
     rxjh_tab = self.rxjh_dlg["SysTabControl32"]#.WrapperObject()#TabControl      #["SysTabControl32"]
     #print type(rxjh_tab.handle)
     #print "%08x" % rxjh_dlg.handle
     #print "%08x" % rxjh_tab.handle
     #print rxjh_tab.Children()
     #(rxjh_dlg.print_control_identifiers())
     for i in range(rxjh_tab.TabCount()):
         print rxjh_tab.GetTabText(i)
     self.lstDlgHandle = findwindows.find_windows(class_name="#32770", parent=rxjh_tab.handle, \
                                    top_level_only = False, visible_only = False)
     print "len: ", len(self.lstDlgHandle)
     for handle in self.lstDlgHandle:
         print "%08x" % handle
         aHwndWrapper = HwndWrapper.HwndWrapper(handle)
         lstWrapper = aHwndWrapper.Children()
         strInfo = ""
         for aWrapper in lstWrapper:
             strInfo = strInfo + '\t' + (aWrapper.WindowText())
         print strInfo
     return
     pass
Example #9
0
def _toggle_notification_area_icons(show_all=True, debug_img=None):
    """
    A helper function to change 'Show All Icons' settings.
    On a succesful execution the function returns an original
    state of 'Show All Icons' checkbox.

    The helper works only for an "English" version of Windows,
    on non-english versions of Windows the 'Notification Area Icons'
    window should be accessed with a localized title"
    """

    app = Application()
    starter = app.start(r'explorer.exe')
    class_name = 'CabinetWClass'

    def _cabinetwclass_exist():
        "Verify if at least one active 'CabinetWClass' window is created"
        l = findwindows.find_windows(active_only=True, class_name=class_name)
        return (len(l) > 0)

    WaitUntil(30, 0.5, _cabinetwclass_exist)
    handle = findwindows.find_windows(active_only=True,
                                      class_name=class_name)[-1]
    window = WindowSpecification({'handle': handle, })
    explorer = Application().Connect(process=window.ProcessID())
    cur_state = None

    try:
        # Go to "Control Panel -> Notification Area Icons"
        window.AddressBandRoot.ClickInput()
        window.TypeKeys(
                    r'control /name Microsoft.NotificationAreaIcons{ENTER}',
                    with_spaces=True,
                    set_foreground=False)
        explorer.WaitCPUUsageLower(threshold=5, timeout=40)

        # Get the new opened applet
        notif_area = explorer.Window_(title="Notification Area Icons",
                                      class_name=class_name)
        cur_state = notif_area.CheckBox.GetCheckState()

        # toggle the checkbox if it differs and close the applet
        if bool(cur_state) != show_all:
            notif_area.CheckBox.ClickInput()
        notif_area.Ok.ClickInput()
        explorer.WaitCPUUsageLower(threshold=5, timeout=40)

    except Exception as e:
        if debug_img:
            from PIL import ImageGrab
            ImageGrab.grab().save("%s.jpg" % (debug_img), "JPEG")
        l = pywinauto.actionlogger.ActionLogger()
        l.log("RuntimeError in _toggle_notification_area_icons")
        raise e

    finally:
        # close the explorer window
        window.Close()

    return cur_state
def present_active_window(window_name):
    app = application.Application()
    handles = findwindows.find_windows()
    for w_handle in handles:
        wind = app.window_(handle=w_handle)
        if window_name == wind.Texts():
            return True
Example #11
0
    def test_find_windows(self):
        """Test if function find_windows() works as expected including raising the exceptions"""
        ctrl_hwnds = [elem.handle for elem in self.dlg.children() if elem.class_name() == 'Edit']
        handles = find_windows(process=self.app.process, class_name='Edit', top_level_only=False)

        self.assertEqual(set(handles), set(ctrl_hwnds))

        self.assertRaises(WindowNotFoundError, find_windows,
                          process=self.app.process, class_name='FakeClassName', found_index=1)
Example #12
0
 def __selectTree(self, path, t=1.5):
     log.info('选择左边树路径{}...'.format(path))
     if not self.tree.IsSelected(path):
         self.tree.Select(path)
         time.sleep(t)
     hwnd = find_windows(top_level_only=False,
                         class_name='#32770',
                         parent=self.__dialog_hwnd)[0]
     self.dialog = self.__app.window(handle=hwnd)
Example #13
0
def _unittests():
    "Do a quick test of finding some windows"
    windows = find_windows(class_name_re="#32770",
                           enabled_only=False,
                           visible_only=False)

    for win in windows:
        print("==" * 20)
        print(handleprops.dumpwindow(win))
Example #14
0
    def tearDown(self):
        "Close the application after tests"
        self.dlg.SendMessage(win32defines.WM_CLOSE)

        # cleanup additional unclosed sampleapps
        l = pywinauto.actionlogger.ActionLogger()
        hndls = findwindows.find_windows(title="TrayMenu")
        for h in hndls:
            l.log("Cleanup unclosed sample app, handle: 0x%x" % (h))
            Application().windows_(handle=h).Close()
Example #15
0
def run_or_raise(class_name, path):
    """Launch a program or focus it if already running."""
    try:
        windows = find_windows(class_name=class_name)
        # XXX: Finds most recent instance, not current workspace's one.
        last_window = windows[-1]
    except IndexError:
        Application().start(path)
    else:
        SetForegroundWindow(last_window)
Example #16
0
    def tearDown(self):
        "Close the application after tests"
        self.dlg.SendMessage(win32defines.WM_CLOSE)

        # cleanup additional unclosed sampleapps
        l = pywinauto.actionlogger.ActionLogger()
        hndls = findwindows.find_windows(title="TrayMenu")
        for h in hndls:
            l.log("Cleanup unclosed sample app, handle: 0x%x" % (h))
            Application().windows_(handle=h).Close()
Example #17
0
def kill_window():
    try:
        for handle in findwindows.find_windows(title_re="(Dropbox Preferences|Preferencias de Dropbox)"):
            app = Application.connect(Application(), handle=handle)
            for window in app.windows_(title_re="(Dropbox Preferences|Preferencias de Dropbox)"):
                logger.warning('Configuration window for Dropbox detected')
                window.Close()
                logger.warning('Configuration window for Dropbox closed')
    except findwindows.WindowNotFoundError:
        pass
Example #18
0
def _unittests():
    "Do a quick test of finding some windows"
    windows = find_windows(
        class_name_re = "#32770",
        enabled_only = False,
        visible_only = False)

    for win in windows:
        print("==" * 20)
        print(handleprops.dumpwindow(win))
Example #19
0
    def tearDown(self):
        "Close the application after tests"
        self.dlg.SendMessage(win32defines.WM_CLOSE)
        self.dlg.WaitNot('ready')

        # cleanup additional unclosed sampleapps
        hndls = findwindows.find_windows(title="TrayMenu")
        if self.app2:
            l = pywinauto.actionlogger.ActionLogger()
            l.log("Cleanup unclosed sample app, handle: 0x%x" % (h))
            self.app2.Close()
Example #20
0
    def testConnect_windowspec(self):
        "Test that connect_() works with a windowspec"
        app1 = Application()
        app1.start(_notepad_exe())
        #unused var: handle = app1.UntitledNotepad.handle

        app_conn = Application()
        try:
            app_conn.connect(title="Untitled - Notepad")
        except findwindows.WindowAmbiguousError:
            wins = findwindows.find_windows(active_only=True, title = "Untitled - Notepad")
            app_conn.connect(handle=wins[0])
        except findwindows.WindowNotFoundError:
            WaitUntil(30, 0.5, lambda: len(findwindows.find_windows(active_only=True, title = "Untitled - Notepad")) > 0)
            wins = findwindows.find_windows(active_only=True, title = "Untitled - Notepad")
            app_conn.connect(handle=wins[0])

        self.assertEqual(app1.process, app_conn.process)

        app_conn.UntitledNotepad.MenuSelect('File->Exit')
Example #21
0
 def find_targets(self):
     """ find target window"""
     
     self.windows = findwindows.find_windows(title_re = "Settings")
     
     if len(self.windows) == 0:
         log.debug('no window found')
     else:
         log.debug(self.windows)
         hwnd = self.windows[0]
         
         self.child_windows = handleprops.children(hwnd)
Example #22
0
def snap_shot(program_dict, location):
    handle = find_windows(**program_dict)[0]
    if handle:
        app = pywinauto.Application().connect(handle=handle)
        dlg = app.window()
        dlg.set_focus()
        sleep(0.2)
        img = dlg.capture_as_image()
        img_name = location
        if not img_name:
            img_name = location + strftime("%Y%m%d_%H%M%S") + '.jpg'
        img.save(img_name)
Example #23
0
    def connect_game(self):
        game_title = self.game_title_entry.get()
        handle = find_windows(title_re=game_title)
        if handle:
            # connect to the game handle
            self.app = pywinauto.Application().connect(handle=handle[0])
            self.dlg = self.app.window()
            self.status.config(text="Connected.")
            print("connected")
            self.update_key_locations()
            self.update_loc_label()

        else:
            self.status.config(text="Can't find the window.")
Example #24
0
 def list_windows(self):
     """
     Returns a list of current open windows.
     Invalid elements such as '' and None are removed.
     Windows O.S ONLY!
     """
     hwnds = findwindows.find_windows()
     names = [handleprops.text(hwnd) for hwnd in hwnds]
     while '' in names:
         names.remove('')
     while None in names:
         names.remove(None)
     logging.debug('Detected following windows: {}'.format(names))
     names.append('')
     return names
Example #25
0
    def testConnect_windowspec(self):
        "Test that connect_() works with a windowspec"
        app1 = Application()
        app1.start_("notepad.exe")
        handle = app1.UntitledNotepad.handle

        app_conn = Application()
        try:
            app_conn.connect_(title = "Untitled - Notepad")
        except findwindows.WindowAmbiguousError:
            wins = findwindows.find_windows(title = "Untitled - Notepad")
            app_conn.connect_(handle = wins[0])

        self.assertEqual(app1.process, app_conn.process)

        app_conn.UntitledNotepad.MenuSelect('File->Exit')
Example #26
0
 def WaitForTitle(self, title, timeout=10, post_delay=0.1):
     t0 = time()
     while time() - t0 < timeout:
         handles = findwindows.find_windows(title_re=title)
         if len(handles) > 0:  #found it
             win = self.browser.window(handle=handles[0])
             try:
                 win.wait('exists enabled visible ready',
                          timeout=timeout - (time() - t0))
             except timings.TimeoutError:
                 raise Exception("Could not find window with title: " +
                                 title)
             sleep(post_delay)
             self.currentWindow = win
             return win
     raise Exception("Could not find window with title: " + title)
Example #27
0
 def getWindowHandles(self) -> list:
     windowList = findwindows.find_windows()  # ウィンドウのハンドル値
     windowHandles = []  # windowListから余計なウィンドウを省いたリスト
     # 先頭5個までのウィンドウだけ扱う
     if len(windowList) > 5:
         num = 5
     else:
         num = len(windowList)
     # print('##########################################')
     for i in range(num):
         element = findwindows.find_element(handle=windowList[i])
         # title='' or 'None'のウィンドウをリストから除外
         if re_search('\'\'', str(element)) is None \
                 and re_search('None', str(element)) is None:
             windowHandles.append(windowList[i])
             # print(str(i) + ':' + str(element))  # debug
     return windowHandles
Example #28
0
def send_test_data(app, test_item, send_port, window, wtbh):
    """

    :param app:
    :param test_item:
    :param send_port:
    :param window:
    :param wtbh:
    """
    test_folder = os.path.abspath(os.path.split(__file__)[0])

    flag = False
    f = None
    t = None
    try:
        f = open(test_item['file'])
        t = serial.Serial(send_port, 9600)
        flag = True
    except IOError:
        print 'open serial port error: ' + send_port
    if not flag:
        f.close()
        return
    try:
        for line in f.readlines():
            items = json.loads(line)
            i = 0
            j = len(items)
            while i < j:
                if items[i]["Value"] is None:
                    print "none"
                    continue
                else:
                    item = repr(items[i]["Value"])
                    #print item
                t.write('a' + item + 'b')

                if find_windows(title_re=u'输入断后标距'):
                    app.window_(title_re=u'输入断后标距').Edit1.TypeKeys(test_item['dhbj'])
                    app.window_(title_re=u'输入断后标距').Button1.Click()

                i += 1
                time.sleep(0.01)

    except IOError, e:
        print e
Example #29
0
def export_view(mod,
                pt_num,
                path_to_views,
                username=ACRONYM,
                password=ACRONYM):
    cmd_display(mod, 'downloading...')
    app = Application().start(
        cmd_line=
        u'"C:\\Program Files (x86)\\Solid Edge TC Manual View\\Solid Edge TC Manual View.exe"'
    )
    app.LoginForm.wait('ready', timeout=30)
    app.LoginForm.Edit5.set_edit_text(username)
    app.LoginForm.Edit4.set_edit_text(password)
    app.LoginForm.Login.click_input()
    time.sleep(5)
    app.PrincipalForm.wait('ready')
    app.PrincipalForm.Edit2.set_edit_text(pt_num)
    app.PrincipalForm.Search.click_input()
    time.sleep(3)
    if findwindows.find_windows(title='Search error'):
        print('Search Error: PT number invalide ')
        window = app.Dialog
        window.wait('ready')
        window.close()
        app.PrincipalForm.type_keys('%{F4}')
    else:
        app.PrincipalForm[u'4'].type_keys(
            path_to_views)  #loop through the  modules files
        app.PrincipalForm[u'3'].type_keys("{DOWN}")
        app.PrincipalForm.Export.click_input()
    app.wait_cpu_usage_lower(
        threshold=5)  # wait until CPU usage is lower than 5%

    def detecting_pdf():
        return any(glob.glob(os.path.join(path_to_views, r'*\*.pdf')))

    wait_until(1000, 5.00, detecting_pdf, True)
    cmd_display(mod, 'exported')
    #close the popup windows & app
    window = app.Dialog
    button = window.OK
    button.click_input()
    #close principal form
    app.PrincipalForm.type_keys('%{F4}')  # close an active window with Alt+F4
    time.sleep(3)
Example #30
0
def work(conf):

    windows = findwindows.find_windows(title_re="Chamber")
    log.debug(windows)
    #log.debug(hex(windows[0]))

    log.debug("##" * 20)

    hwnd = 0x00010266

    listbox = ListBoxWrapper(hwnd)

    ct = listbox.ItemCount()

    log.debug(ct)

    for text in listbox.ItemTexts():
        log.debug(text)
Example #31
0
    def conect_pc(self, host):
        try:
            play = "mstsc  /console /v: %s:3389" % (host)
            app = application.Application(backend='uia').start(play)

            #一定要1秒中的停留窗口的时间
            time.sleep(1)
            w_handle = findwindows.find_windows(title=u'远程桌面连接',
                                                class_name='#32770')[0]
            aduc_window = app.window_(handle=w_handle)
            # aduc_window.print_control_identifiers()

            # b = aduc_window.child_window(title=u'是(&Y)', class_name="Button")
            # b.print_control_identifiers()
            tip = u'不再询问我是否连接到此计算机(&D)'
            # OK = u'取消(&C)'
            OK = u'是(&Y)'
            # aduc_window[tip].Check()
            #模拟点击操作
            aduc_window[OK].Click()

        except Exception as e:
            print(e)
Example #32
0
    else:
    # return True to pass the event to other handlers
        return True

    # zwraca false jesli to male a badz duze A co powoduje ze nie
    # przekazuje klikniecia dalej
    # return (event.Ascii not in (ord('a'), ord('A')))


# initial running programs list
app = application.Application()
# cala lista
app_list = findwindows.enum_windows()
# UWAGA ZWRACA LISTE
try:
    temp_list = findwindows.find_windows(title_re = '.*XnView')
    xnview_app = int(temp_list[0])

    # polaczenie i otworzenie dialogu
    # dlg = app.connect_(handle = int(app_list[0]))
except:
    print('Nothing from app list is running. Continue anyway? y/n.')
    should_continue = raw_input()

    if should_continue is 'y':
        pass
    else:
        sys.exit(0)


# create a hook manager
Example #33
0
def TaskBarHandle():
    "Return the first window that has a class name 'Shell_TrayWnd'"
    return findwindows.find_windows(class_name="Shell_TrayWnd")[0]
def present_active_windows():
    global rootLogger
    handles = findwindows.find_windows()
    for w_handle in handles:
        wind = app.window_(handle=w_handle)
        rootLogger.info(wind.Texts())
Example #35
0
 def test_find_windows_re(self):
     "Test for bug #90: A crash in 'find_windows' when called with 'title_re' argument"
     self.dlgspec.Wait('visible')
     windows = findwindows.find_windows(title_re="Untitled - Notepad")
     self.assertTrue(len(windows) >= 1)
Example #36
0
                if find_windows(title_re=u'输入断后标距'):
                    app.window_(title_re=u'输入断后标距').Edit1.TypeKeys(test_item['dhbj'])
                    app.window_(title_re=u'输入断后标距').Button1.Click()

                i += 1
                time.sleep(0.01)

    except IOError, e:
        print e
    t.close()
    f.close()
    #print 'closed the file and serial port'
    time.sleep(1)
    
    if find_windows(title_re=u'输入断后标距'):
        app.window_(title_re=u'输入断后标距').Edit1.TypeKeys(test_item['dhbj'])
        app.window_(title_re=u'输入断后标距').Button1.Click()
    time.sleep(1)
    img = window.CaptureAsImage()
    imgURl = unicode(test_folder, encoding="GBK") + '\picture\\'+test_item['type']+'\\'+wtbh + '.gif'
    img.save(imgURl)



if __name__ == '__main__':
    case = {'type': 'WN', 'file': 'D:\\test\\1.txt', 'check': [
        {'sheet_id': "270a1da6-2045-405a-ae77-18c0c98c1edd", 'cell_name': 'D29', 'min_value': '122',
         'max_value': '123'},{'sheet_id': "270a1da6-2045-405a-ae77-18c0c98c1edd", 'cell_name': 'G29', 'min_value': '120',
         'max_value': '121'}]}
    check_test_data(case, '20140801095404')
Example #37
0
def TaskBarHandle():
    "Return the first window that has a class name 'Shell_TrayWnd'"
    return findwindows.find_windows(class_name = "Shell_TrayWnd")[0]
Example #38
0
 def check_passphrase_windows_closed():
   return (len(findwindows.find_windows(title=u'Pageant: Enter Passphrase', class_name='#32770')) == 0)
Example #39
0
 def _cabinetwclass_exist():
     "Verify if at least one active 'CabinetWClass' window is created"
     l = findwindows.find_windows(active_only=True, class_name=class_name)
     return (len(l) > 0)
Example #40
0
def _toggle_notification_area_icons(show_all=True, debug_img=None):
    """
    A helper function to change 'Show All Icons' settings.
    On a succesful execution the function returns an original
    state of 'Show All Icons' checkbox.

    The helper works only for an "English" version of Windows,
    on non-english versions of Windows the 'Notification Area Icons'
    window should be accessed with a localized title"
    """

    app = Application()
    starter = app.start(r'explorer.exe')
    class_name = 'CabinetWClass'

    def _cabinetwclass_exist():
        "Verify if at least one active 'CabinetWClass' window is created"
        l = findwindows.find_windows(active_only=True, class_name=class_name)
        return (len(l) > 0)

    WaitUntil(_ready_timeout, _retry_interval, _cabinetwclass_exist)
    handle = findwindows.find_windows(active_only=True,
                                      class_name=class_name)[-1]
    window = WindowSpecification({'handle': handle, })
    explorer = Application().Connect(process=window.ProcessID())
    cur_state = None

    try:
        # Go to "Control Panel -> Notification Area Icons"
        window.Wait("ready", timeout=_ready_timeout)
        window.AddressBandRoot.ClickInput()
        window.TypeKeys(
                    r'control /name Microsoft.NotificationAreaIcons',
                    with_spaces=True,
                    set_foreground=True)
        # Send 'ENTER' separately, this is to make sure 
        # the window focus hasn't accidentally been lost
        window.TypeKeys(
                    '{ENTER}',
                    with_spaces=True,
                    set_foreground=True)
        explorer.WaitCPUUsageLower(threshold=5, timeout=_ready_timeout)

        # Get the new opened applet
        notif_area = explorer.Window_(title="Notification Area Icons",
                                      class_name=class_name)
        notif_area.Wait("ready", timeout=_ready_timeout)
        cur_state = notif_area.CheckBox.GetCheckState()

        # toggle the checkbox if it differs and close the applet
        if bool(cur_state) != show_all:
            notif_area.CheckBox.ClickInput()
        notif_area.Ok.ClickInput()
        explorer.WaitCPUUsageLower(threshold=5, timeout=_ready_timeout)

    except Exception as e:
        if debug_img:
            from PIL import ImageGrab
            ImageGrab.grab().save("%s.jpg" % (debug_img), "JPEG")
        l = pywinauto.actionlogger.ActionLogger()
        l.log("RuntimeError in _toggle_notification_area_icons")
        raise e

    finally:
        # close the explorer window
        window.Close()

    return cur_state
Example #41
0
try:
    dlg2 = timings.WaitUntilPasses(20, 0.5, lambda: app.window_(title='번개3'))
    btn_ctrl2 = dlg2.Button1
    btn_ctrl2.Click()
except:
    ff.write("    ERROR in Location 2\n")
    ff.close()
    sys.exit()

time.sleep(120)
try:
    os.system("taskkill /im NKmini.exe")
except:
    ff.write("    ERROR in Locaiton 3\n")
    ff.close()
    sys.exit()

time.sleep(1)
try:
    title2 = findwindows.find_windows(title='',
                                      class_name='#32770',
                                      control_id=0)[0]
    dlg2 = timings.WaitUntilPasses(20, 0.5, lambda: app.window_(handle=title2))
    btn_ctrl2 = dlg2.Button0
    btn_ctrl2.Click()
    ff.write("    -- success at: " + time.ctime(time.time()) + "\n")

except:
    ff.write("    ERROR in Location 4\n")

ff.close()
Example #42
0
#! python3

import pyautogui
from pywinauto import findwindows, Application
from sys import exit
from time import sleep

pyautogui.FAILSAFE = True

try:
    app = Application().connect(handle=findwindows.find_windows(
        title='Skype')[0])
except:
    print('Skype is not running. Exiting..')
    exit()

print('Send to...')
sendTo = input().split(",")
print('Message:')
msg = input()

skype = app['Skype']
skypeLoc = skype.rectangle()
searchBarLoc = (skypeLoc.left + 50, skypeLoc.top + 150)
addButtonLoc = (skypeLoc.right - 70, skypeLoc.top + 130)

skype.set_focus()
pyautogui.click(*searchBarLoc)
sleep(0.25)
first = sendTo.pop(0).strip()
pyautogui.typewrite(first, 0.1)
Example #43
0
def Last_Second_Save():
    # start = time.time()
    hndls = None
    hndls = findwindows.find_windows()
    imgs = None
    imgs = []
    for hndl in hndls:
        if ((handleprops.exstyle(hndl) == 256 or handleprops.exstyle(hndl)
             == 786688 or handleprops.exstyle(hndl) == 262400
             or handleprops.exstyle(hndl) == 65792 or handleprops.exstyle(hndl)
             == 2097408 or handleprops.exstyle(hndl) == 262416
             or handleprops.exstyle(hndl) == 327937
             or handleprops.exstyle(hndl) == 0)
                and not (handleprops.text(hndl) == None
                         or handleprops.text(hndl) == "")):
            print(
                str(handleprops.text(hndl)) + " - " +
                str(handleprops.exstyle(hndl)))
            if (str(handleprops.text(hndl)).strip() == ""):
                continue
            else:
                try:
                    app = None
                    app = hwndwrapper.HwndWrapper(hndl)
                    # app.set_focus()
                    win32functions.WaitGuiThreadIdle(hndl)
                    if app.is_minimized():
                        app.restore()
                        time.sleep(0.25)
                    win32functions.WaitGuiThreadIdle(hndl)
                    app.set_focus()
                    win32functions.WaitGuiThreadIdle(hndl)
                    rect = None
                    rect = handleprops.rectangle(hndl)
                    win32functions.WaitGuiThreadIdle(hndl)
                    box = None
                    box = (rect.left, rect.top, rect.right, rect.bottom)
                    img = None
                    img = getRectAsImage(box)
                    imgs.append(img)
                    # time.sleep(0.1)
                except:
                    # print("ERROR --- "+(str(handleprops.text(hndl)) + " - " + str(handleprops.processid(hndl))))
                    # print("Unexpected error:", sys.exc_info()[0])
                    continue
    #START IF#
    if len(imgs) > 0:
        sqrt = math.sqrt(len(imgs))
        # print(sqrt)
        if sqrt > int(sqrt):
            if len(imgs) == 1:
                matrix_col, matrix_row = (1, 1)
            else:
                matrix_col, matrix_row = (int(sqrt), int(sqrt))
                addition = [0]
                while (matrix_col * matrix_row) < len(imgs):
                    if (addition[0] == 0):
                        matrix_col += 1
                        addition[0] = 1
                    else:
                        matrix_row += 1
                        addition[0] = 0
        else:
            matrix_col, matrix_row = (int(sqrt), int(sqrt))

        # print("MATRIX: " + str(matrix_row) + "x" + str(matrix_col))
        finalRes_width = 960 * matrix_col
        finalRes_height = 540 * matrix_row
        result = Image.new("RGB", (finalRes_width, finalRes_height))
        # print("RESULT IMAGE SIZE: " + str(result.size))
        perImg_width = 960
        perImg_height = 540
        lst_counter = 0
        # print("NUMBER OF IMGS: " + str(len(imgs)))
        for col in range(matrix_col):
            for row in range(matrix_row):
                if len(imgs) > lst_counter:
                    imgs[lst_counter].thumbnail((perImg_width, perImg_height),
                                                Image.LANCZOS)
                    x = col * perImg_width
                    y = row * perImg_height
                    w, h = imgs[lst_counter].size
                    result.paste(imgs[lst_counter], (x, y, x + w, y + h))
                    lst_counter += 1

        now = datetime.now()
        name = ("LastSecondSave-" + str(now.year) + "-" + str(now.month) +
                "-" + str(now.day) + "-" + str(now.hour) + "-" +
                str(now.minute))
        homeDir = os.path.expanduser("~")
        if os.path.isdir(homeDir + "\\LastSecondSave"):
            result.save(homeDir + "\\LastSecondSave\\" + name + ".jpg")
        else:
            os.mkdir(homeDir + "\\LastSecondSave")
            result.save(homeDir + "\\LastSecondSave\\" + name + ".jpg")
Example #44
0
CHANNEL = "#carpedm20"

irc = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
irc.connect ((HOST, PORT))
# print irc.recv (4096)

irc.send("PASS %s\r\n" % PASS)
irc.send("NICK %s\r\n" % NICK)
irc.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
irc.send("JOIN %s\r\n" % CHANNEL)

readbuffer = ""

app = Application()
#windows = find_windows(title_re=u".*VisualBoy.*")
windows = find_windows(title_re=u".*GameBoy.*")
print windows

if windows:
    w = app.window_(handle = windows[0])
    title_name = w.WindowText()

    # 'Style', 'ClientRects', 'IsEnabled', 'Fonts', 'IsUnicode', 'ContextHelpID', 'IsVisible', 
    # 'Rectangle', 'UserData', 'MenuItems', 'FriendlyClassName', 'ControlCount', 'Texts', 'ExStyle', 'ControlID', 'Class
    prop = pywinauto.controls.HwndWrapper.GetDialogPropsFromHandle(windows[0])[0]



while (1):
    data = irc.recv(1024)
    if data.find ( 'PRIVMSG' ) != -1:
 def all_components(self):
     handles = findwindows.find_windows(process=self.process_id)
     return self._components_helper(handles)