Ejemplo n.º 1
0
class RemoteMemoryBlockTests(unittest.TestCase):
    "Unit tests for RemoteMemoryBlock"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.ctrl = self.dlg.TreeView.WrapperObject()

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()

    def testGuardSignatureCorruption(self):
        mem = RemoteMemoryBlock(self.ctrl, 16)
        buf = ctypes.create_string_buffer(24)
        
        self.assertRaises(Exception, mem.Write, buf)
        
        mem.size = 24 # test hack
        self.assertRaises(Exception, mem.Write, buf)
Ejemplo n.º 2
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
Ejemplo n.º 3
0
class ControlStateTests(unittest.TestCase):

    """Unit tests for control states"""

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.Select(4)
        self.ctrl = self.dlg.EditBox.WrapperObject()

    def tearDown(self):
        """Close the application after tests"""
        self.app.kill_()

    def test_VerifyEnabled(self):
        """test for verify_enabled"""
        self.assertRaises(ElementNotEnabled, self.ctrl.verify_enabled)

    def test_VerifyVisible(self):
        """test for verify_visible"""
        self.dlg.TabControl.Select(3)
        self.assertRaises(ElementNotVisible, self.ctrl.verify_visible)
Ejemplo n.º 4
0
    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.Fast()

        self.app = Application()
        self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe"))
        self.app2 = Application().start(_notepad_exe())
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        app = Application()
        app.start_(controlspy_folder + "Tab.exe")

        self.texts = [
            "Pluto", "Neptune", "Uranus",
            "Saturn", "Jupiter", "Mars",
            "Earth", "Venus", "Mercury", "Sun"]

        self.rects = [
            RECT(2,2,80,21),
            RECT(80,2,174,21),
            RECT(174,2,261,21),
            RECT(2,21,91,40),
            RECT(91,21,180,40),
            RECT(180,21,261,40),
            RECT(2,40,64,59),
            RECT(64,40,131,59),
            RECT(131,40,206,59),
            RECT(206,40,261,59),
        ]

        self.app = app
        self.dlg = app.MicrosoftControlSpy
        self.ctrl = app.MicrosoftControlSpy.TabControl.WrapperObject()
Ejemplo n.º 6
0
    def SendKeysToAllWindows(self, title_regex):
        "Sends the keystroke to all windows whose title matches the regex"

        # We need to call find_windows on our own because Application.connect_ will
        # call find_window and throw if it finds more than one match.
        all_matches = pywinauto.findwindows.find_windows(title_re=title_regex)

        # We need to store all window handles that have been sent keys in order
        # to avoid reactivating windows and doing unnecesary refreshes. This is a
        # side effect of having to call Application.connect_ on each regex match.
        # We need to loop through each open window collection to support edge
        # cases like Google Canary where the Window title is identical to Chrome.
        processed_handles = []

        for win in all_matches:
            app = Application()
            app.connect_(handle=win)
            open_windows = app.windows_(title_re=title_regex)

            for openwin in open_windows:
                if openwin.handle in processed_handles:
                    continue

                openwin.TypeKeys("{F5}")
                processed_handles.append(openwin.handle)
                time.sleep(1)
Ejemplo n.º 7
0
class GetDialogPropsFromHandleTest(unittest.TestCase):

    """Unit tests for mouse actions of the HwndWrapper class"""

    def setUp(self):
        """Set some data and ensure the application is in the state we want"""
        Timings.Fast()

        self.app = Application()
        self.app.start(_notepad_exe())

        self.dlg = self.app.UntitledNotepad
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)

    def tearDown(self):
        """Close the application after tests"""
        # close the application
        #self.dlg.type_keys("%{F4}")
        self.dlg.Close(0.5)
        self.app.kill_()


    def test_GetDialogPropsFromHandle(self):
        """Test some small stuff regarding GetDialogPropsFromHandle"""
        props_from_handle = GetDialogPropsFromHandle(self.dlg.handle)
        props_from_dialog = GetDialogPropsFromHandle(self.dlg)
        #unused var: props_from_ctrl = GetDialogPropsFromHandle(self.ctrl)

        self.assertEquals(props_from_handle, props_from_dialog)
Ejemplo n.º 8
0
class SendKeysModifiersTests(unittest.TestCase):
    "Unit tests for the Sendkeys module (modifiers)"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""
        self.app = Application().start(os.path.join(mfc_samples_folder, u"CtrlTest.exe"))

        self.dlg = self.app.Control_Test_App

    def tearDown(self):
        "Close the application after tests"
        try:
            self.dlg.Close(0.5)
        except Exception:
            pass
        finally:
            self.app.kill_()

    def testModifiersForFewChars(self):
        "Make sure that repeated action works"
        SendKeys("%(SC)", pause = .3)
        dlg = self.app.Window_(title='Using C++ Derived Class')
        dlg.Wait('ready')
        dlg.Done.CloseClick()
        dlg.WaitNot('visible')
        
        SendKeys("%(H{LEFT}{UP}{ENTER})", pause = .3)
        dlg = self.app.Window_(title='Sample Dialog with spin controls')
        dlg.Wait('ready')
        dlg.Done.CloseClick()
        dlg.WaitNot('visible')
class UnicodeEditTestCases(unittest.TestCase):

    """Unit tests for the EditWrapper class using Unicode strings"""

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application().Start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe"))

        self.dlg = self.app.Common_Controls_Sample
        self.dlg.TabControl.Select("CAnimateCtrl")

        self.ctrl = self.dlg.AnimationFileEdit.WrapperObject()

    def tearDown(self):
        "Close the application after tests"
        self.app.kill_()

    def testSetEditTextWithUnicode(self):
        "Test setting Unicode text by the SetEditText method of the edit control"
        self.ctrl.Select()
        self.ctrl.SetEditText(579)
        self.assertEquals("\n".join(self.ctrl.Texts()[1:]), "579")

        self.ctrl.SetEditText(333, pos_start=1, pos_end=2)
        self.assertEquals("\n".join(self.ctrl.Texts()[1:]), "53339")
Ejemplo n.º 10
0
    def testClickCustomizeButton(self):
        "Test click on the 'show hidden icons' button"

        # Minimize to tray
        self.dlg.Minimize()
        self.dlg.WaitNot("active")

        # Make sure that the hidden icons area is enabled
        orig_hid_state = _toggle_notification_area_icons(show_all=False, debug_img="%s_01.jpg" % (self.id()))

        # Run one more instance of the sample app
        # hopefully one of the icons moves into the hidden area
        app2 = Application()
        app2.start_(os.path.join(mfc_samples_folder, u"TrayMenu.exe"))
        dlg2 = app2.TrayMenu
        dlg2.Wait("visible")
        dlg2.Minimize()
        dlg2.WaitNot("active")

        # Test click on "Show Hidden Icons" button
        taskbar.ShowHiddenIconsButton.ClickInput()
        niow_dlg = taskbar.explorer_app.Window_(class_name="NotifyIconOverflowWindow")
        niow_dlg.OverflowNotificationAreaToolbar.Wait("ready", timeout=30)
        niow_dlg.SysLink.ClickInput()
        nai = taskbar.explorer_app.Window_(title="Notification Area Icons", class_name="CabinetWClass")
        origAlwaysShow = nai.CheckBox.GetCheckState()
        if not origAlwaysShow:
            nai.CheckBox.ClickInput()
        nai.OK.Click()

        # Restore Notification Area settings
        _toggle_notification_area_icons(show_all=orig_hid_state, debug_img="%s_02.jpg" % (self.id()))

        # close the second sample app
        dlg2.SendMessage(win32defines.WM_CLOSE)
Ejemplo n.º 11
0
    def testGetitem(self):
        "Test that __getitem__() works correctly"
        app = Application()
        app.start(_notepad_exe())

        try:
            app['blahblah']
        except Exception:
            pass


        #prev_timeout = application.window_find_timeout
        #application.window_find_timeout = .1
        self.assertRaises(
            findbestmatch.MatchError,
            app['blahblah']['not here'].__getitem__, 'handle')

        self.assertEqual(
            app[u'Unt\xeftledNotepad'].handle,
            app.window_(title = "Untitled - Notepad").handle)

        app.UntitledNotepad.MenuSelect("Help->About Notepad")

        self.assertEqual(
            app['AboutNotepad'].handle,
            app.window_(title = "About Notepad").handle)

        app.AboutNotepad.Ok.Click()
        app.UntitledNotepad.MenuSelect("File->Exit")
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        app = Application()

        import os.path
        path = os.path.split(__file__)[0]

        test_file = os.path.join(path, "test.txt")

        with codecs.open(test_file, mode="rb", encoding='utf-8') as f:
            self.test_data = f.read()
        # remove the BOM if it exists
        self.test_data = self.test_data.replace(repr("\xef\xbb\xbf"), "")
        #self.test_data = self.test_data.encode('utf-8', 'ignore') # XXX: decode raises UnicodeEncodeError even if 'ignore' is used!
        print('self.test_data:')
        print(self.test_data.encode('utf-8', 'ignore'))

        app.start_("Notepad.exe " + test_file, timeout=20)

        self.app = app
        self.dlg = app.UntitledNotepad
        self.ctrl = self.dlg.Edit.WrapperObject()

        self.old_pos = self.dlg.Rectangle

        self.dlg.MoveWindow(10, 10, 400, 400)
Ejemplo n.º 13
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application

        app = Application()
        app.start_(os.path.join(mfc_samples_folder, u"RowList.exe"))

        self.texts = [
            (u"Yellow", u"255", u"255", u"0", u"40", u"240", u"120", u"Neutral"),
            (u"Red", u"255", u"0", u"0", u"0", u"240", u"120", u"Warm"),
            (u"Green", u"0", u"255", u"0", u"80", u"240", u"120", u"Cool"),
            (u"Magenta", u"255", u"0", u"255", u"200", u"240", u"120", u"Warm"),
            (u"Cyan", u"0", u"255", u"255", u"120", u"240", u"120", u"Cool"),
            (u"Blue", u"0", u"0", u"255", u"160", u"240", u"120", u"Cool"),
            (u"Gray", u"192", u"192", u"192", u"160", u"0", u"181", u"Neutral"),
        ]

        self.app = app
        self.dlg = app.RowListSampleApplication  # top_window_()
        self.ctrl = app.RowListSampleApplication.ListView.WrapperObject()
        self.dlg.Toolbar.Button(0).Click()  # switch to icon view
        self.dlg.Toolbar.Button(6).Click()  # switch off states
Ejemplo n.º 14
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application

        app = Application()
        app.start_(os.path.join(mfc_samples_folder, "RowList.exe"), timeout=20)

        self.texts = [u"Color", u"Red", u"Green", u"Blue", u"Hue", u"Sat", u"Lum", u"Type"]
        self.item_rects = [
            RECT(0, 0, 150, 19),
            RECT(150, 0, 200, 19),
            RECT(200, 0, 250, 19),
            RECT(250, 0, 300, 19),
            RECT(300, 0, 400, 19),
            RECT(400, 0, 450, 19),
            RECT(450, 0, 500, 19),
            RECT(500, 0, 650, 19),
        ]

        self.app = app
        self.dlg = app.RowListSampleApplication  # top_window_()
        self.ctrl = app.RowListSampleApplication.Header.WrapperObject()
class GetDialogPropsFromHandleTest(unittest.TestCase):
    "Unit tests for mouse actions of the HwndWrapper class"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application()
        self.app.start_("notepad.exe")

        self.dlg = self.app.UntitledNotepad
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)

    def tearDown(self):
        "Close the application after tests"
        # close the application
        self.dlg.TypeKeys("%{F4}")


    def test_GetDialogPropsFromHandle(self):
        "Test some small stuff regarding GetDialogPropsFromHandle"

        props_from_handle = GetDialogPropsFromHandle(self.dlg.handle)

        props_from_dialog = GetDialogPropsFromHandle(self.dlg)

        props_from_ctrl = GetDialogPropsFromHandle(self.ctrl)

        self.assertEquals(props_from_handle, props_from_dialog)
Ejemplo n.º 16
0
    def test_getattribute(self):
        """Test that __getattribute__() works correctly"""
        app = Application()
        app.start(_notepad_exe())

        self.assertRaises(
            findbestmatch.MatchError,
            app.blahblah.__getattribute__, 'handle')

        self.assertEqual(
            app.UntitledNotepad.handle,
            app.window_(title = "Untitled - Notepad").handle)

        app.UntitledNotepad.MenuSelect("Help->About Notepad")

        # I think it's OK that this no longer raises a matcherror
        # just because the window is not enabled - doesn't mean you
        # should not be able to access it at all!
        #self.assertRaises(findbestmatch.MatchError,
        #    app.Notepad.__getattribute__, 'handle')

        self.assertEqual(
            app.AboutNotepad.handle,
            app.window_(title = "About Notepad").handle)

        app.AboutNotepad.Ok.Click()
        app.UntitledNotepad.MenuSelect("File->Exit")
Ejemplo n.º 17
0
    def test_is64bitprocess(self):
        "Make sure a 64-bit process detection returns correct results"
 
        if is_x64_OS():
            # Test a 32-bit app running on x64
            expected_is64bit = False
            if is_x64_Python():
                exe32bit = os.path.join(os.path.dirname(__file__),
                              r"..\..\apps\MFC_samples\RowList.exe")
                app = Application().start_(exe32bit, timeout=20)
                pid = app.RowListSampleApplication.ProcessID()
                res_is64bit = is64bitprocess(pid)
                try:
                    self.assertEquals(expected_is64bit, res_is64bit)
                finally:
                    # make sure to close an additional app we have opened
                    app.kill_()

                # setup expected for a 64-bit app on x64
                expected_is64bit = True
        else:
            # setup expected for a 32-bit app on x86
            expected_is64bit = False

        # test native Notepad app
        res_is64bit = is64bitprocess(self.app.UntitledNotepad.ProcessID())
        self.assertEquals(expected_is64bit, res_is64bit)
Ejemplo n.º 18
0
class NotepadRegressionTests(unittest.TestCase):
    "Regression unit tests for Notepad"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        self.app = Application()
        self.app.start_(_notepad_exe())

        self.dlg = self.app.Window_(title='Untitled - Notepad', class_name='Notepad')
        self.ctrl = HwndWrapper(self.dlg.Edit.handle)
        self.dlg.edit.SetEditText("Here is some text\r\n and some more")

        self.app2 = Application.start(_notepad_exe())


    def tearDown(self):
        "Close the application after tests"

        # close the application
        try:
            self.dlg.Close(0.5)
            if self.app.Notepad["Do&n't Save"].Exists():
                self.app.Notepad["Do&n't Save"].Click()
                self.app.Notepad["Do&n't Save"].WaitNot('visible')
        except Exception: # timings.TimeoutError:
            pass
        finally:
            self.app.kill_()
        self.app2.kill_()

    def testMenuSelectNotepad_bug(self):
        "In notepad - MenuSelect Edit->Paste did not work"

        text = b'Here are some unicode characters \xef\xfc\r\n'
        self.app2.UntitledNotepad.Edit.Wait('enabled')
        time.sleep(0.3)
        self.app2.UntitledNotepad.Edit.SetEditText(text)
        time.sleep(0.3)
        self.assertEquals(self.app2.UntitledNotepad.Edit.TextBlock().encode(locale.getpreferredencoding()), text)

        Timings.after_menu_wait = .7
        self.app2.UntitledNotepad.MenuSelect("Edit->Select All")
        time.sleep(0.3)
        self.app2.UntitledNotepad.MenuSelect("Edit->Copy")
        time.sleep(0.3)
        self.assertEquals(clipboard.GetData().encode(locale.getpreferredencoding()), text)

        self.dlg.SetFocus()
        self.dlg.MenuSelect("Edit->Select All")
        self.dlg.MenuSelect("Edit->Paste")
        self.dlg.MenuSelect("Edit->Paste")
        self.dlg.MenuSelect("Edit->Paste")

        self.app2.UntitledNotepad.MenuSelect("File->Exit")
        self.app2.Window_(title='Notepad', class_name='#32770')["Don't save"].Click()

        self.assertEquals(self.dlg.Edit.TextBlock().encode(locale.getpreferredencoding()), text*3)
Ejemplo n.º 19
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        self.texts = [u'', u'New', u'Open', u'Save', u'Cut', u'Copy', u'Paste', u'Print', u'About', u'Help']

        # start the application
        from pywinauto.application import Application
        app = Application()
        app.start_(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))
        #app.start_(os.path.join(controlspy_folder, "Tooltip.exe"))

        self.app = app
        self.dlg = app.Common_Controls_Sample
        
        self.dlg.TabControl.Select(u'CToolBarCtrl')

        '''
        tips = app.windows_(
            visible_only = False,
            enabled_only = False,
            top_level_only = False,
            class_name = "tooltips_class32")
        '''

        self.ctrl = self.dlg.Toolbar.GetToolTipsControl() #WrapHandle(tips[1])
Ejemplo n.º 20
0
class ClipboardTestCases(unittest.TestCase):
    "Unit tests for the clipboard"

    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""
        EmptyClipboard()
        self.app1 = Application().start("notepad.exe")
        self.app2 = Application().start("notepad.exe")

        self.app1.UntitledNotepad.MoveWindow(RECT(0, 0, 200, 200))
        self.app2.UntitledNotepad.MoveWindow(RECT(0, 200, 200, 400))


    def tearDown(self):
        "Close the application after tests"
        # close the application
        self.app1.UntitledNotepad.MenuSelect('File -> Exit')
        if self.app1.Notepad["Do&n't Save"].Exists():
            self.app1.Notepad["Do&n't Save"].Click()
        self.app1.kill_()

        self.app2.UntitledNotepad.MenuSelect('File -> Exit')
        if self.app2.Notepad["Do&n't Save"].Exists():
            self.app2.Notepad["Do&n't Save"].Click()
        self.app2.kill_()


    def testGetClipBoardFormats(self):
        typetext(self.app1, "here we are")
        copytext(self.app1)

        self.assertEquals(GetClipboardFormats(), [13, 16, 1, 7])

    def testGetFormatName(self):
        typetext(self.app1, "here we are")
        copytext(self.app1)

        self.assertEquals(
            [GetFormatName(f) for f in GetClipboardFormats()],
            ['CF_UNICODETEXT', 'CF_LOCALE', 'CF_TEXT', 'CF_OEMTEXT']
        )

    def testBug1452832(self):
        """Failing test for sourceforge bug 1452832

        Where GetData was not closing the clipboard. FIXED.
        """
        self.app1.UntitledNotepad.MenuSelect("Edit->Select All Ctrl+A")
        typetext(self.app1, "some text")
        copytext(self.app1)

        # was not closing the clipboard!
        data = GetData()
        self.assertEquals(data, "some text")


        self.assertEquals(gettext(self.app2), "")
        pastetext(self.app2)
        self.assertEquals(gettext(self.app2), "some text")
Ejemplo n.º 21
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""
        self.screen_w = win32api.GetSystemMetrics(0)

        # start the application
        from pywinauto.application import Application
        app = Application()
        app.start_(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))

        self.texts = [
            u"CTreeCtrl", u"CAnimateCtrl", u"CToolBarCtrl", 
            u"CDateTimeCtrl", u"CMonthCalCtrl"]

        self.rects = [
            RECT(2,   2, 58,  20), 
            RECT(58,  2, 130, 20), 
            RECT(130, 2, 201, 20), 
            RECT(201, 2, 281, 20), 
            RECT(281, 2, 360, 20)
        ]

        self.app = app
        self.dlg = app.CommonControlsSample
        self.ctrl = app.CommonControlsSample.TabControl.WrapperObject() 
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        app = Application()
        app.start_(os.path.join(controlspy_folder, "Tree View.exe"))

        self.root_text = "The Planets"
        self.texts = [
            ("Mercury", '57,910,000', '4,880', '3.30e23'),
            ("Venus",   '108,200,000', '12,103.6', '4.869e24'),
            ("Earth",   '149,600,000', '12,756.3', '5.9736e24'),
            ("Mars",    '227,940,000', '6,794', '6.4219e23'),
            ("Jupiter", '778,330,000', '142,984', '1.900e27'),
            ("Saturn",  '1,429,400,000', '120,536', '5.68e26'),
            ("Uranus",  '2,870,990,000', '51,118', '8.683e25'),
            ("Neptune", '4,504,000,000', '49,532', '1.0247e26'),
            ("Pluto",   '5,913,520,000', '2,274', '1.27e22'),
         ]

        self.app = app
        self.dlg = app.MicrosoftControlSpy #top_window_()
        self.ctrl = app.MicrosoftControlSpy.TreeView.WrapperObject()
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        app = Application()
        app.start_(os.path.join(controlspy_folder, "Tab.exe"))

        self.texts = [
            "Pluto", "Neptune", "Uranus",
            "Saturn", "Jupiter", "Mars",
            "Earth", "Venus", "Mercury", "Sun"]

        self.rects = [
            RECT(2,2,63,21),
            RECT(63,2,141,21),
            RECT(141,2,212,21),
            RECT(212,2,280,21),
            RECT(280,2,348,21),
            RECT(2,21,68,40),
            RECT(68,21,135,40),
            RECT(135,21,207,40),
            RECT(207,21,287,40),
            RECT(287,21,348,40),
        ]

        self.app = app
        self.dlg = app.MicrosoftControlSpy
        self.ctrl = app.MicrosoftControlSpy.TabControl.WrapperObject()
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""

        # start the application
        from pywinauto.application import Application
        app = Application()

        import os.path
        path = os.path.split(__file__)[0]

        test_file = os.path.join(path, "test.txt")

        self.test_data = open(test_file, "rb").read()
        # remove the BOM if it exists
        self.test_data = self.test_data.replace("\xef\xbb\xbf", "")
        self.test_data = self.test_data.decode('utf-8')

        app.start_("Notepad.exe " + test_file)

        self.app = app
        self.dlg = app.UntitledNotepad
        self.ctrl = self.dlg.Edit.WrapperObject()

        self.old_pos = self.dlg.Rectangle

        self.dlg.MoveWindow(10, 10, 400, 400)
class ButtonOwnerdrawTestCases(unittest.TestCase):

    """Unit tests for the ButtonWrapper(ownerdraw button)"""

    def setUp(self):

        """Start the sample application. Open a tab with ownerdraw button."""

        # start the application
        self.app = Application().Start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe"))
        # open the needed tab
        self.app.active_().TabControl.Select(1)

    def tearDown(self):

        """Close the application after tests"""

        self.app.kill_()

    def test_NeedsImageProp(self):

        """test whether an image needs to be saved with the properties"""

        active_window = self.app.active_()
        self.assertEquals(active_window.Button2._NeedsImageProp, True)
        self.assertIn('Image', active_window.Button2.GetProperties())
Ejemplo n.º 26
0
 def setUp(self):
     """Start the application set some data and ensure the application
     is in the state we want it."""
     app = Application()
     app.start_(os.path.join(mfc_samples_folder, u"TrayMenu.exe"))
     self.app = app
     self.dlg = app.TrayMenu  # top_window_()
     self.dlg.Wait("ready")
Ejemplo n.º 27
0
    def setUp(self):
        """Start the application set some data and ensure the application
        is in the state we want it."""
        self.app1 = Application.start("notepad.exe")
        self.app2 = Application.start("notepad.exe")

        self.app1.UntitledNotepad.MoveWindow(RECT(0, 0, 200, 200))
        self.app2.UntitledNotepad.MoveWindow(RECT(0, 200, 200, 400))
Ejemplo n.º 28
0
 def test_cpu_usage(self):
     """Verify that cpu_usage() works correctly"""
     app = Application()
     self.assertRaises(AppNotConnected, app.cpu_usage)
     app.start(_notepad_exe())
     self.assertEquals(0.0 <= app.cpu_usage() <= 100.0, True)
     app.UntitledNotepad.MenuSelect("File->Exit")
     app.UntitledNotepad.WaitNot('exists')
Ejemplo n.º 29
0
def OnMouseEvent(event):
    global last_event_time
    # if this is the first action - remember the start time of the script
    if not last_event_time:
        last_event_time = event.Time
    app = Application()

    # wrap the window that is coming from the event
    if event.Window:
        wrapped = app.window_(handle = event.Window)
    else:
        wrapped = None

    # if there was no previous message
    global last_message
    if last_message is None:
        last_message = event.MessageName
        return True


    # get the button pressed
    button = ""
    if "right" in event.MessageName and "right" in last_message:
        button = "Right"
    elif "left" in event.MessageName and "left" in last_message:
        button = "Left"

    toplevel = ""
    if wrapped and not wrapped.IsDialog():
        toplevel = '.Window_(title = "%s", class_name = "%s")' %(
            wrapped.TopLevelParent().window_text(), wrapped.TopLevelParent().class_name())

    if "up" in event.MessageName and "down" in last_message:
        print "time.sleep(%d)"% (event.Time - last_event_time)
        print 'app%s.Window_(title = "%s", class_name = "%s").%sClickInput()'%(
            toplevel,
            wrapped.WindowText(),
            wrapped.Class(),
            button)

    last_event_time = event.Time
    last_message = event.MessageName


  # called when mouse events are received
  #print 'MessageName:',event.MessageName
#  print 'Message:',event.Message
#  print 'Time:',event.Time
  #print 'Window:',event.Window
#  print 'WindowName:',event.WindowName
#  print 'Position:',event.Position
#  print 'Wheel:',event.Wheel
#  print 'Injected:',event.Injected
#  print '---'

  # return True to pass the event to other handlers
    return True
Ejemplo n.º 30
0
 def setUp(self):
     """Start the application set some data and ensure the application
     is in the state we want it."""
     self.tm = _ready_timeout
     app = Application()
     app.start(os.path.join(mfc_samples_folder, u"TrayMenu.exe"))
     self.app = app
     self.dlg = app.top_window_()
     self.dlg.Wait('ready', timeout=self.tm)
Ejemplo n.º 31
0
    def test_click_on_button_email_for_one_page_without_ocr_for_distributing_open_source_code(self):
        app = Application(backend="uia")

        url_page = "https://www.yellowpages.ca/bus/Nova-Scotia/Middle-Sackville/After-Warranty-Automotive-Repair/5803120.html?what=car+repair&where=Halifax+NS&useContext=true"

        time.sleep(5)

        # Ouvrir l'application Microsoft Edge
        app.start("C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe")

        time.sleep(10)

        print(url_page)

        pywinauto.keyboard.send_keys(url_page)

        time.sleep(3)

        # Press the 'Enter' button
        pywinauto.keyboard.send_keys('{ENTER}')

        time.sleep(7)

        # Move the mouse to the 'Message' button
        # Click the 'Message' button
        pywinauto.mouse.click(button='left', coords=(480, 330))

        time.sleep(4)

        # Move the mouse to the 'Your email' textbox
        # Click on the 'Your email' textbox
        pywinauto.mouse.click(button='left', coords=(420, 260))

        time.sleep(4)

        # Write my name in the 'Your email' textbox
        myEmail = ""
        pywinauto.keyboard.send_keys(myEmail)

        time.sleep(4)

        # Move the mouse to the 'First name' textbox
        # Click on the 'First name' textbox
        pywinauto.mouse.click(button='left', coords=(430, 310))

        time.sleep(4)

        # Write my name in the 'First name' textbox
        myFirstName = ""
        pywinauto.keyboard.send_keys(myFirstName)

        time.sleep(4)

        # Move the mouse to the 'Last name' textbox
        # Click on the 'Last name' textbox
        pywinauto.mouse.click(button='left', coords=(700, 310))

        time.sleep(4)

        # Write my name in the 'Last name' textbox
        myLastName = ""
        pywinauto.keyboard.send_keys(myLastName)

        time.sleep(4)

        # Move the mouse to the 'Message' textbox
        # Click on the 'Objet du message' textbox
        pywinauto.mouse.click(button='left', coords=(430, 400))

        time.sleep(4)

        # Write my name in the 'Message' textbox
        myMessage = (
                ""
        )
        pywinauto.keyboard.send_keys(myMessage)

        time.sleep(4)

        # Click on the 'Envoyer' button
        #pywinauto.mouse.click(button='left', coords=(920, 620))

        time.sleep(4)

        # Close an active window with Alt+F4
        #pywinauto.keyboard.send_keys('%{F4}')

        time.sleep(4)
Ejemplo n.º 32
0
 def __init__(self):
     self.app = Application()
     self.x = []
     self.z = []
Ejemplo n.º 33
0
from pywinauto.application import Application
# Run a target application
app = Application().start(r"C:\apache-jmeter-3.0\bin\jmeter.bat")
# print app
# Select a template item
app.ApacheJmeter.menu_select("File->Templates")
Ejemplo n.º 34
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_elements(active_only=True, class_name=class_name)
        return (len(l) > 0)

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

    try:
        # Go to "Control Panel -> Notification Area Icons"
        window.Wait("ready", timeout=_ready_timeout)
        window.AddressBandRoot.click_input()
        window.type_keys(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.type_keys('{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.click_input()
        notif_area.Ok.click_input()
        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
Ejemplo n.º 35
0
import pyautogui
import time

import pendulum
from pywinauto.application import Application

app = Application().start(
    cmd_line=
    u'"C://Users//YASH RAJ MANI//AppData//Local//Microsoft//Teams//current//Teams.exe"'
)

pendulum.now()
current = pendulum.now().to_day_datetime_string()
print(current)
time.sleep(7)
'''
subprocess.call('C://Users//YASH RAJ MANI//AppData//Local//Microsoft//Teams//current//Teams.exe')
print("hey, THIS IS YASH ! ")
print("LOADING >>>>>>>>>>>>>>>>")
'''

#MYTIMETABLE:
#maths th join done!

############## MONDAY ###########################
if "Mon" in current:
    if "8:" in current:
        print("EEE1001")
        pyautogui.click(271, 622)
        print("EEE th ")
        pyautogui.click('Join now')
###FEA=sheet.cell_value(16,1)
###BLOWOUT_FEA=sheet.cell_value(17,1)
#APPNAME=sheet.cell_value(13,1)
###findstring="for"
###APPNAME="PLS-CADD - "+BAK
###CIRCUIT_KV=str(BAK)
###if findstring in APPNAME:
###    APPNAME=APPNAME[:-15]
###    CIRCUIT_KV=BAK[:-23]
###    APPNAME=APPNAME+".xyz"
###else:
###    APPNAME=APPNAME[:-11]
###    Circuit_KV=BAK[:-19]
###    APPNAME=APPNAME+".xyz"
#app = Application().connect(title_re="PLS-CADD - ALP_SUC_1_69kV_qsi2019.xyz")
app = Application().connect(title_re=APPNAME)

## close TIN
app.top_window().menu_select("Terrain-> TIN -> Display_Options")
app.Ground_TIN_Display_Options.render_triangles.uncheck()
app.Ground_TIN_Display_Options.OK.click()
sleep(1.0)
## Step 6 Creat MaxOP Detection
app.top_window().menu_select("Line-> Edit")
try:
    dlg = app.window(title_re="Warning")
    app.dlg.no.click()
except:
    pass
app.Line.Copy.click()
try:
Ejemplo n.º 37
0
 def open_app(self, last_dir, app_name):
     # open app
     path = os.path.join(os.path.abspath('.'), last_dir, app_name)
     app_start = Application().start(path)
     # 绑定进程,class_name和title是可选的,可以灵活使用,如果找到多个货没有找到该程序,程序会报错
     self.__app = Application().connect(class_name='PuTTYConfigBox')
Ejemplo n.º 38
0
from pywinauto.application import Application
import time

app = Application().start(
    '"C:\Program Files (x86)\PesticideModels\TOPRice\TOPrice.exe"')
time.sleep(1)

# app['TOPRice_2.4.2_CN'].menu_select("File")

dlg_spec = app['TOPRice_2.4.2_CN']
print(dlg_spec.print_control_identifiers())
Ejemplo n.º 39
0
 def setUp(self):
     """Start the application and ensure it's in the state we want"""
     self.app = Application().start(
         os.path.join(mfc_samples(), u"CtrlTest.exe"))
     self.dlg = self.app.Control_Test_App
Ejemplo n.º 40
0
class SendKeysTests(unittest.TestCase):
    """Unit tests for the Sendkeys module"""
    def setUp(self):
        """Start the application set some data and ensure the application is in the state we want it."""
        if sys.platform == 'win32':
            self.app = Application()
            self.app.start(_notepad_exe())
            self.dlg = self.app.UntitledNotepad
            self.ctrl = self.dlg.Edit
        else:
            self.app = subprocess.Popen("exec " + _test_app(), shell=True)
            time.sleep(0.1)
            mouse.click(coords=(300, 300))
            time.sleep(0.1)

    def tearDown(self):
        """Close the application after tests"""
        if sys.platform == 'win32':
            try:
                self.dlg.close(0.1)
            except Exception:  # TimeoutError:
                pass
            try:
                if self.app.Notepad["Do&n't Save"].exists():
                    self.app.Notepad["Do&n't Save"].click()
                    self.app.Notepad["Do&n't Save"].wait_not('visible')
            except Exception:  # TimeoutError:
                pass
            finally:
                if self.dlg.exists(timeout=0.1):
                    self.app.kill()
        else:
            # call Popen.kill() on Linux since Application.kill() is not implemented yet
            self.app.kill()

    def receive_text(self):
        """Receive data from text field"""
        received = ' '
        if sys.platform == 'win32':
            received = self.ctrl.text_block()
        else:
            time.sleep(0.2)
            send_keys('^a')
            time.sleep(0.2)
            send_keys('^c')
            send_keys('{RIGHT}')
            received = clipboard.get_data()
        return received

    def __run_NormalCharacters_with_options(self, **args):
        """Make sure that sending any character in range """
        #unused var: missed = []
        for i in range(32, 127):

            # skip characters that must be escaped
            if chr(i) in '~!@#$%^&*()_+{}|:"<>? ':
                continue

            send_keys(chr(i), pause=.001, **args)
            received = self.receive_text()[-1]

            self.assertEqual(i, ord(received))

    # Space tests
    def testNormalWithSpaces(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_spaces=True)

    def testNormalWithoutSpaces(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_spaces=False)

    def testSpaceWithSpaces(self):
        """Make sure that with spaces option works"""
        send_keys(" \t \t ", pause=.001, with_spaces=True)
        received = self.receive_text()
        self.assertEqual("   ", received)

    def testSpaceWithoutSpaces(self):
        """Make sure that with spaces option works"""
        send_keys(" \t \t ", pause=.001, with_spaces=False)
        received = self.receive_text()
        self.assertEqual("", received)

    # Tab tests
    def testNormalWithTabs(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_tabs=True)

    def testNormalWithoutTabs(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_tabs=False)

    def testTabWithTabs(self):
        """Make sure that with spaces option works"""
        send_keys("\t \t \t", pause=.1, with_tabs=True)
        received = self.receive_text()
        self.assertEqual("\t\t\t", received)

    def testTabWithoutTabs(self):
        """Make sure that with spaces option works"""
        send_keys("\t a\t b\t", pause=.1, with_tabs=False)
        received = self.receive_text()
        self.assertEqual("ab", received)

    def testTab(self):
        """Make sure that with spaces option works"""
        send_keys("{TAB}  {TAB} ", pause=.3)
        received = self.receive_text()
        self.assertEqual("\t\t", received)

    # Newline tests
    def testNormalWithNewlines(self):
        """Make sure that with spaces option works"""
        self.__run_NormalCharacters_with_options(with_newlines=True)

    def testNormalWithoutNewlines(self):
        """Make sure that with_newlines option works"""
        self.__run_NormalCharacters_with_options(with_newlines=False)

    def testNewlinesWithNewlines(self):
        """Make sure that with_newlines option works"""
        send_keys("\t \t \t a~\tb\nc", pause=.5, with_newlines=True)
        received = self.receive_text()
        if sys.platform == 'win32':
            self.assertEqual("a\r\nb\r\nc", received)
        else:
            self.assertEqual("a\nb\nc", received)

    def testNewlinesWithoutNewlines(self):
        """"Make sure that with_newlines option works"""
        send_keys("\t \t \t\na", pause=.01, with_newlines=False)
        received = self.receive_text()
        self.assertEqual("a", received)

    #def testANSIExtendedCharacters(self):
    #    "Make sure that sending any character in range "
    #    #self.cmd = Application()
    #    #self.cmd.start("cmd.exe", create_new_console=True, wait_for_idle=False)
    #    ActionLogger().log('Preferred encoding: ' + locale.getpreferredencoding())
    #
    #    #os.system("chcp 850")
    #    matched = 0
    #    extended_chars = b"\x81\x82\x83\xa1\xe1\xff"
    #    for char in extended_chars:

    #        if six.PY3:
    #            c = str(char)
    #        else:
    #            c = char.decode(locale.getpreferredencoding()) #'cp850')
    #        send_keys(c, pause = .01)
    #        received = self.receive_text()[-1]

    #        if c == received:
    #            matched += 1
    #        else:
    #            print("expected %s, recieved %s"% (
    #                repr(c), repr(received)))

    #    self.assertEqual(matched, len(extended_chars))

    def testCharsThatMustBeEscaped(self):
        """Make sure that escaping characters works"""
        send_keys("{%}{^}{+}{(}{)}{{}{}}{~}")
        received = self.receive_text()
        self.assertEqual("%^+(){}~", received)

    def testIncorrectCases(self):
        """Make sure that incorrect key sequences raise an exception"""
        self.assertRaises(KeySequenceError, send_keys, "{ENTER")
        self.assertRaises(KeySequenceError, send_keys, "ENTER)")
        self.assertRaises(RuntimeError, send_keys, "%{Enterius}")
        self.assertRaises(KeySequenceError, send_keys, "{PAUSE small}")

        try:
            send_keys("{ENTER five}")
        except KeySequenceError as exc:
            self.assertEqual("invalid repetition count five", str(exc))

        try:
            send_keys("ENTER}")
        except KeySequenceError as exc:
            self.assertEqual("`}` should be preceeded by `{`", str(exc))

    def testKeyDescription(self):
        """Test KeyAction._"""
        self.assertEqual("<X>", str(KeyAction("X")))
        self.assertEqual("<Y down>", str(KeyAction("Y", up=False)))
        self.assertEqual("<Y up>", str(KeyAction("Y", down=False)))
        #self.assertEqual("<ENTER>", str(VirtualKeyAction(13))) # == "<VK_RETURN>" in Python 2.7 (TODO)
        if sys.platform == 'win32':
            self.assertEqual("<PAUSE 1.00>", str(PauseAction(1.0)))

    def testRepetition(self):
        """Make sure that repeated action works"""
        send_keys("{TAB 3}{PAUSE 0.5}{F 3}", pause=.3)
        received = self.receive_text()
        self.assertEqual("\t\t\tFFF", received)

    def testShiftModifier(self):
        """Make sure that Shift modifier works"""
        send_keys("+(a)")
        received = self.receive_text()
        self.assertEqual("A", received)

    if sys.platform != 'win32':

        def testAltModifier(self):
            """Make sure that alt modifier works"""
            clipboard.set_data('abc')
            # check alt via opening edit menu and paste text from clipboard
            time.sleep(0.3)
            send_keys('%(e)')
            time.sleep(0.3)
            send_keys('{ENTER}')
            received = self.receive_text()
            self.assertEqual('abc', received)
Ejemplo n.º 41
0
    def set_driver(self):
        self.var = {'_last_': False}
        self.snippet = {}
        self.current_page = '通用'
        self.db = {}
        self.http = {}
        self.windows = {}
        self.baseurl = {}
        self.action = {}
        if self.platform.lower() == 'desktop':
            if self.browserName.lower() == 'ie':
                #capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
                #capabilities['acceptInsecureCerts'] = True
                if self.executable_path:
                    self.driver = webdriver.Ie(
                        executable_path=self.executable_path)
                else:
                    self.driver = webdriver.Ie()
            elif self.browserName.lower() == 'firefox':
                profile = webdriver.FirefoxProfile()
                profile.accept_untrusted_certs = True

                options = webdriver.FirefoxOptions()
                # 如果配置了 headless 模式
                if self.headless:
                    options.set_headless()
                    # options.add_argument('-headless')
                    options.add_argument('--disable-gpu')
                    options.add_argument("--no-sandbox")
                    options.add_argument('window-size=1920x1080')

                if self.executable_path:
                    self.driver = webdriver.Firefox(
                        firefox_profile=profile,
                        firefox_options=options,
                        executable_path=self.executable_path)
                else:
                    self.driver = webdriver.Firefox(firefox_profile=profile,
                                                    firefox_options=options)
                self.driver.maximize_window()
            elif self.browserName.lower() == 'chrome':
                options = webdriver.ChromeOptions()

                # 如果配置了 headless 模式
                if self.headless:
                    options.add_argument('--headless')
                    options.add_argument('--disable-gpu')
                    options.add_argument("--no-sandbox")
                    options.add_argument('window-size=1920x1080')

                options.add_argument("--start-maximized")
                options.add_argument('--ignore-certificate-errors')
                # 指定浏览器分辨率,当"--start-maximized"无效时使用
                # options.add_argument('window-size=1920x1080')
                prefs = {}
                prefs["credentials_enable_service"] = False
                prefs["profile.password_manager_enabled"] = False
                options.add_experimental_option("prefs", prefs)
                options.add_argument('disable-infobars')
                if self.executable_path:
                    self.driver = webdriver.Chrome(
                        options=options, executable_path=self.executable_path)
                else:
                    self.driver = webdriver.Chrome(options=options)
            else:
                raise Exception(
                    'Error: this browser is not supported or mistake name:%s' %
                    self.browserName)
            # 等待元素超时时间
            self.driver.implicitly_wait(element_wait_timeout)  # seconds
            # 页面刷新超时时间
            self.driver.set_page_load_timeout(page_flash_timeout)  # seconds

        elif self.platform.lower() == 'ios':
            from appium import webdriver as appdriver
            if not self.driver:
                self.driver = appdriver.Remote(self.server_url,
                                               self.desired_caps)

        elif self.platform.lower() == 'android':
            from appium import webdriver as appdriver
            if not self.driver:
                self.driver = appdriver.Remote(self.server_url,
                                               self.desired_caps)

        elif self.platform.lower() == 'windows':
            from pywinauto.application import Application
            from sweetest.keywords.windows import Windows
            self.desired_caps.pop('platformName')
            backend = self.desired_caps.pop('backend', 'win32')
            _path = ''
            if self.desired_caps.get('#path'):
                _path = self.desired_caps.pop('#path')
                _backend = self.desired_caps.pop('#backend')

            if self.desired_caps.get('cmd_line'):
                app = Application(backend).start(**self.desired_caps)
            elif self.desired_caps.get('path'):
                app = Application(backend).connect(**self.desired_caps)
            else:
                raise Exception('Error: Windows GUI start/connect args error')
            self.windows['default'] = Windows(app)

            if _path:
                _app = Application(_backend).connect(path=_path)
                self.windows['#'] = Windows(_app)
Ejemplo n.º 42
0
    def test_click_on_button_email_for_all_pages_without_ocr_for_distributing_open_source_hydrogen_technologies_for_car_repair_in_canada(self):
        app = Application(backend="uia")

        contacts = [
            # edmonton
            {
                'location': 'Edmonton+AB',
                'start': '1',
                'number_of_page': '20'
            },

            # victoria
            {
                'location': 'Victoria+BC',
                'start': '1',
                'number_of_page': '8'
            },

            # winnipeg
            {
                'location': 'Winnipeg+MB',
                'start': '1',
                'number_of_page': '14'
            },

            # fredericton
            {
                'location': 'Fredericton+NB',
                'start': '1',
                'number_of_page': '4'
            },

            # saint john
            {
                'location': 'Aeroport+De+Saint-Jean-De-Terre-Neuve+St+Johns+NL',
                'start': '1',
                'number_of_page': '6'
            },

            # halifax
            {
                'location': 'Halifax+NS',
                'start': '1',
                'number_of_page': '10'
            },

            # yellowknife
            {
                'location': 'Yellowknife+NT',
                'start': '1',
                'number_of_page': '1'
            },

            # iqaluit
            {
                'location': 'Iqaluit+NU',
                'start': '1',
                'number_of_page': '1'
            },

            # toronto
            {
                'location': 'Toronto+ON',
                'start': '1',
                'number_of_page': '60'
            },

            # charlottetown
            {
                'location': 'Charlottetown+PE',
                'start': '1',
                'number_of_page': '4'
            },

            # quebec
            {
                'location': 'Quebec+QC',
                'start': '1',
                'number_of_page': '23'
            },

            # regina
            {
                'location': 'Regina+SK',
                'start': '1',
                'number_of_page': '4'
            },

            # whitehorse
            {
                'location': 'Whitehorse+YT',
                'start': '1',
                'number_of_page': '2'
            }
        ]

        for contact in contacts:
            try:
                location = contact.get("location")
                start = int(contact.get("start"))
                number_of_pages = int(contact.get("number_of_page"))

                i_1 = 1

                for i in range(start, number_of_pages + 1):
                    url_page_results = "https://www.yellowpages.ca/search/si/" + str(i) + "/car+repair/" + location

                    print("url_page_results : " + url_page_results)

                    html_search = requests.get(url_page_results)

                    soup_search = BeautifulSoup(html_search.content, 'html.parser')

                    if soup_search.find("div", {"class": "resultList"}) is not None:
                        if soup_search\
                                .find("div", {"class": "resultList"})\
                                .find("div", {"class": "listing"}) is not None:
                            results = soup_search\
                                .find("div", {"class": "resultList"})\
                                .find_all("div", {"class": "listing"})

                            for result in results:
                                if result.find("li", {"class": "mlr__item--message"}) is not None:
                                    url_page = "https://www.yellowpages.ca" + result\
                                        .find("link", {"itemprop": "url"})\
                                        .get("href")

                                    print("url_page " + str(i_1) + " : " + url_page)

                                    time.sleep(5)

                                    # Ouvrir l'application Microsoft Edge
                                    app.start("C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe")

                                    time.sleep(10)

                                    pywinauto.keyboard.send_keys(url_page)

                                    time.sleep(3)

                                    # Press the 'Enter' button
                                    pywinauto.keyboard.send_keys('{ENTER}')

                                    time.sleep(7)

                                    # Move the mouse to the 'Message' button
                                    # Click the 'Message' button
                                    pywinauto.mouse.click(button='left', coords=(480, 330))

                                    time.sleep(4)

                                    # Move the mouse to the 'Your email' textbox
                                    # Click on the 'Your email' textbox
                                    pywinauto.mouse.click(button='left', coords=(420, 260))

                                    time.sleep(4)

                                    # Write my name in the 'Your email' textbox
                                    myEmail = ""
                                    pywinauto.keyboard.send_keys(myEmail)

                                    time.sleep(4)

                                    # Move the mouse to the 'First name' textbox
                                    # Click on the 'First name' textbox
                                    pywinauto.mouse.click(button='left', coords=(430, 310))

                                    time.sleep(4)

                                    # Write my name in the 'First name' textbox
                                    myFirstName = ""
                                    pywinauto.keyboard.send_keys(myFirstName)

                                    time.sleep(4)

                                    # Move the mouse to the 'Last name' textbox
                                    # Click on the 'Last name' textbox
                                    pywinauto.mouse.click(button='left', coords=(700, 310))

                                    time.sleep(4)

                                    # Write my name in the 'Last name' textbox
                                    myLastName = ""
                                    pywinauto.keyboard.send_keys(myLastName)

                                    time.sleep(4)

                                    # Move the mouse to the 'Message' textbox
                                    # Click on the 'Objet du message' textbox
                                    pywinauto.mouse.click(button='left', coords=(430, 400))

                                    time.sleep(4)

                                    # Write my name in the 'Message' textbox
                                    myMessage = (
                                            ""
                                    )
                                    pywinauto.keyboard.send_keys(myMessage)

                                    time.sleep(4)

                                    # Click on the 'Envoyer' button
                                    pywinauto.mouse.move(coords=(920, 620))
                                    # pywinauto.mouse.click(button='left', coords=(920, 620))

                                    time.sleep(4)

                                    # Close an active window with Alt+F4
                                    pywinauto.keyboard.send_keys('%{F4}')

                                    time.sleep(4)
                                else:
                                    print(str(i_1) + " div class mlr__item--message is not present")

                                i_1 += 1
                        else:
                            print("div class listing is not present")
                    else:
                        print("div class resultList is not present")
            except Exception as e:
                print("error : " + str(e))
Ejemplo n.º 43
0
from pywinauto.application import Application
import time
app = Application().start(r"7z1900-x64.exe")
time.sleep(1)
app['Dialog']['InstallButton'].click()
time.sleep(1)
app['Dialog']['否(&N)'].click()
time.sleep(1)
app['Dialog']['Close'].click()
Ejemplo n.º 44
0
 def __init__(self, target):
     self.application = WinApp(backend="win32").start(target)
     self.main_window = self.application.window(title="Free Address Book")
     self.main_window.wait("visible")
     self.groups = GroupHelper(self)
import pyautogui as pag
from pywinauto.application import Application
import time

start_time = time.time()


app = Application(backend="uia")
app.connect(path='C:\Program Files (x86)\Rozm\Rozm.exe', title='Rozm')
app.Dialog.menu_select("Правка->Очистити")
app.Dialog.type_keys("Здравствуйте,_я_ваш_новий_голосовой_помошник_Анатоль._Чем_могу_бить_полезен")
pag.press('home')
app.Dialog['Читай'].select()




#print(app.top_window().descendants(control_type="MenuBar")[1].items())
#print(pag.position())
#field_start_pos = (5, 57)
#read_pos = (124, 35)
#rozm = app.Dialog
#rozm.MenuSelect()
#rozm['Правка']
#rozm['Вставит']
#app.start('C:\Program Files (x86)\Rozm\Rozm.exe')
#print(app.your_dialog.print_control_identifiers())
#app["Приложение -> Текст"]
#pag.click(field_start_pos)
#pag.typewrite("")
#pag.typewrite(["home"])
Ejemplo n.º 46
0
 def __init__(self,exe_path,backend="uia"):
     try:
         self.app=Application(backend=backend).start(cmd_line=exe_path)
         logger.info("{}程序启动成功".format(exe_path))
     except:
         logger.exception("{}程序启动失败".format(exe_path))
Ejemplo n.º 47
0
EChecked.appendChild(EChecked_text)
UserNo = doc.createElement('UserNo')
LoginInfo.appendChild(UserNo)
UserNo_text = doc.createTextNode('ADMIN')
UserNo.appendChild(UserNo_text)
Passwd = doc.createElement('Passwd')
LoginInfo.appendChild(Passwd)
Passwd_text = doc.createTextNode('nx9TmpOReOkzt/Eb1jYlOw==')
Passwd.appendChild(Passwd_text)
SystemRent = doc.createElement('SystemRent')
config.appendChild(SystemRent)
Skin = doc.createElement('Skin')
SystemRent.appendChild(Skin)
Skin_text = doc.createTextNode('\n\t\t')
Skin.appendChild(Skin_text)
ShowHelpFrom = doc.createElement('ShowHelpFrom')
SystemRent.appendChild(ShowHelpFrom)
ShowHelpFrom_text = doc.createTextNode('Hidden')
ShowHelpFrom.appendChild(ShowHelpFrom_text)
ImportExportCOMBINESUBMIT = doc.createElement('ImportExportCOMBINESUBMIT')
config.appendChild(ImportExportCOMBINESUBMIT)
COMBINESUBMIT = doc.createElement('COMBINESUBMIT')
ImportExportCOMBINESUBMIT.appendChild(COMBINESUBMIT)
COMBINESUBMIT_text = doc.createTextNode('C:\\Users\\zhaoning\\Desktop\\')
COMBINESUBMIT.appendChild(COMBINESUBMIT_text)

f = open('Local.xml', 'w')
doc.writexml(f, newl='\n', addindent='\t', encoding='utf-8')
f.close()
app = Application().start(path_dir_finally + '\\' + mystr[0] + '\\' +
                          mystr[0] + '\\' + "iTapManage.exe")
Ejemplo n.º 48
0
# path = 'C:\\Program Files (x86)\\Default Company Name\\SetupHocTiengNhat'
path = 'E:\\hong\\Debug'
base = 'C:\\Users\\Admin\\Documents\\rule\\edit_rule'
for link in os.listdir(base):
	if 'txt' in link:
		links = (base + '\\' + link).replace('\\','\\\\')
		with open(links, 'r',encoding='utf-8') as rules:
			data = rules.read()
		rules.close()
# print(data)

for files in os.listdir(path):
    if files == 'Tornado.exe':
        file_name = (path + '\\' + files).replace('\\', '\\\\')
        app = Application(backend="win32").start(file_name)
        time.sleep(1)
        app.top_window_().TypeKeys("tornado{TAB}tornado{TAB}{END}{BACKSPACE}211.109.9.60{TAB}19100{TAB 2}{ENTER}")
        time.sleep(5)
        app.top_window_().TypeKeys("{TAB 9}")
        app.top_window_().TypeKeys("{TAB 3}{DOWN}{RIGHT}{DOWN 12    }{RIGHT}{ENTER}{TAB 2}")
        time.sleep(1)


        app.top_window_().TypeKeys("{DOWN 5}{RIGHT}")
        time.sleep(1)
        app.top_window_().TypeKeys("{ENTER}{TAB 2}{DOWN 6}{RIGHT}")
        time.sleep(1)
        # app.top_window_().TypeKeys("{ENTER}{TAB 2}{DOWN 27}{RIGHT}")
        # time.sleep(1)
        # app.top_window_().TypeKeys("{ENTER}{TAB 2}{DOWN 104}{RIGHT}")
 def app(self):
     if self._app is None:
         return Application().start(
             path=Windows_Controller(self.oem).statusapp)
     return self._app
Ejemplo n.º 50
0
# -*- coding: utf-8 -*-
"""
Created on Thu Oct  3 10:58:37 2019

"""
import sys
from pywinauto.application import Application

cfgpath = '\\\czcifi02.tymphany.com\LV_Instr\LV_Doc\V300\SW\LINAK\LinakConfigFiles\SettlingRig_15mms_0_440mm_hrbitov_v01.cfg'

#sys.exit(1)

app = Application().start("C:\Program Files (x86)\Linak\LinProgrammer\LinProgrammer.exe")
dlg = app['LinProgrammer. Version 1.45']
buttonOK = dlg['Load file']
buttonOK.click()

#app.window(title="Open")['File name:Edit'].set_text('ahoj')

dlgload = app.window(title="Open")
editFilename = dlgload['File name:Edit']
editFilename.set_text(cfgpath)
buttonOpwn = dlgload['Cancel']
#buttonCancel.click()
#'Open'

#app['LinProgrammer. Version 1.45']['Load file'].click()


sys.exit(0)
Ejemplo n.º 51
0
 def down1(self):
     self.output.setText("")
     name = self.name.text()
     efrm = self.frm.text()
     eto = self.to.text()
     eto = int(eto) + 1
     self.out = []
     n1 = name.replace(" ", "-")
     link = "https://www1.ondramanice.co/" + str(n1) + "/watch-" + str(
         n1) + "-episode-"
     i = 10
     k = 1
     tab = 1
     flag = 0
     opts = Options()
     opts.add_extension("I:/projects/py/AdBlock_v3.34.0.crx")
     opts.add_extension(
         "Pop-up-blocker-for-Chrome™-Poper-Blocker_v4.0.8.crx")
     driver = webdriver.Chrome(options=opts)
     for a in range(int(efrm), int(eto)):
         x = a
         driver.get(link + str(a) + "-online")
         try:
             driver.find_element_by_link_text("Download")
         except NoSuchElementException:
             if a >= int(efrm) & flag == 0:
                 driver.quit()
                 self.output.setText("Error - Check Series Name")
             else:
                 self.output.setText("Error - Episode " + str(a) +
                                     " Not Present")
                 if (a == x):
                     continue
         else:
             el = driver.find_element_by_link_text(
                 "Download").get_attribute("href")
             driver.get(el)
         try:
             driver.find_element_by_partial_link_text("DOWNLOAD (360P -")
         except NoSuchElementException:
             try:
                 driver.find_element_by_partial_link_text("DOWNLOAD (4")
             except NoSuchElementException:
                 try:
                     driver.find_element_by_partial_link_text(
                         "DOWNLOAD RAPIDVIDEO")
                 except NoSuchElementException:
                     i = 2
                     if (a == x):
                         self.out.append(a)
                         continue
                 else:
                     d = driver.find_element_by_partial_link_text(
                         "DOWNLOAD RAPIDVIDEO").get_attribute("href")
                     driver.get(d)
                 ra = 50
                 while ra != 0:
                     try:
                         driver.find_element_by_partial_link_text(
                             "Download")
                     except NoSuchElementException:
                         driver.get(d)
                         ra = ra - 1
                     else:
                         ra = 0
                         i = 1
                         down = driver.find_element_by_partial_link_text(
                             "Download").get_attribute("href")
                 if (ra <= 0):
                     try:
                         driver.find_element_by_partial_link_text(
                             "Download")
                     except NoSuchElementException:
                         if (a == x):
                             self.out.append(a)
                             continue
                     else:
                         ra = 0
                         i = 1
                         down = driver.find_element_by_partial_link_text(
                             "Download").get_attribute("href")
             else:
                 i = 1
                 down = driver.find_element_by_partial_link_text(
                     "DOWNLOAD (").get_attribute("href")
         else:
             i = 1
             down = driver.find_element_by_partial_link_text(
                 "DOWNLOAD (360P -").get_attribute("href")
         if tab == 1:
             pyautogui.hotkey('ctrl', '1')
             tab = 2
         if (i == 1):
             app = Application().start(
                 "C:/Program Files (x86)/Internet Download Manager/IDMan.exe"
             )
             # app = Application().start("C:/Program Files (x86)/Internet Download Manager/IDMan.exe")
             pyautogui.press('alt')
             pyautogui.press('enter')
             pyautogui.press('enter')
             pyautogui.typewrite(down, interval=0.02)
             pyautogui.press('enter')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('enter')
             pyautogui.typewrite(str(name) + " Episode " + str(a) + ".mp4",
                                 interval=0.08)
             pyautogui.press('enter')
             pyautogui.press('tab')
             pyautogui.press('enter')
             flag = 1
         else:
             driver.quit()
             self.output.setText("No Link Found")
     driver.quit()
     if len(self.out) != 0:
         out1 = ""
         for i in self.out:
             out1 = str(out1) + str(i) + ","
         self.output.setText("Error Episodes - " + str(out1))
     else:
         self.output.setText("Downloads Sucessfully Added..")
Ejemplo n.º 52
0
 def down2(self):
     self.output.setText("")
     name = self.name.text()
     efrm = self.frm.text()
     eto = self.to.text()
     self.out = []
     eto = int(eto) + 1
     n1 = name.replace(" ", "-")
     link = "http://kissdrama.club/" + str(n1) + "/"
     i = 3
     opts = Options()
     opts.add_extension("I:/projects/py/AdBlock_v3.34.0.crx")
     opts.add_extension(
         "Pop-up-blocker-for-Chrome™-Poper-Blocker_v4.0.8.crx")
     driver = webdriver.Chrome(options=opts)
     driver.get(link)
     pyautogui.hotkey('ctrl', '2')
     pyautogui.hotkey('ctrl', 'w')
     pyautogui.hotkey('ctrl', '2')
     pyautogui.hotkey('ctrl', 'w')
     pyautogui.hotkey('ctrl', '1')
     try:
         driver.find_element_by_partial_link_text("Download")
     except NoSuchElementException:
         driver.quit()
         self.output.setText("Wrong Name Check Name")
     else:
         d = driver.find_element_by_partial_link_text(
             "Download").get_attribute("href")
         driver.get(d)
     for a in range(int(efrm), int(eto)):
         x = a
         if a << 10:
             de = driver.find_element_by_partial_link_text(
                 "Download Episode 0" + str(a))
             de.click()
             driver.switch_to.window(driver.window_handles[1])
         else:
             de = driver.find_element_by_partial_link_text(
                 "Download Episode " + str(a))
             de.click()
             pyautogui.hotkey('ctrl', 'w')
             de.click()
             driver.switch_to.window(driver.window_handles[1])
         try:
             driver.find_element_by_partial_link_text("Rapid")
         except NoSuchElementException:
             i = 2
             if (a == x):
                 self.out.append(a)
                 continue
         else:
             ra = driver.find_element_by_link_text("Rapid")
             ra.click()
             driver.switch_to.window(driver.window_handles[2])
             try:
                 driver.find_element_by_partial_link_text("DOWNLOAD")
             except NoSuchElementException:
                 if (a == x):
                     self.out.append(a)
                     continue
             else:
                 down = driver.find_element_by_partial_link_text(
                     "DOWNLOAD").get_attribute("href")
                 i = 1
         if (i == 1):
             app = Application().start(
                 "C:/Program Files (x86)/Internet Download Manager/IDMan.exe"
             )
             # app = Application().start("C:/Program Files (x86)/Internet Download Manager/IDMan.exe")
             pyautogui.press('alt')
             pyautogui.press('enter')
             pyautogui.press('enter')
             pyautogui.typewrite(down)
             pyautogui.press('enter')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('tab')
             pyautogui.press('enter')
             pyautogui.typewrite(str(name) + " Episode " + str(a) + ".mp4",
                                 interval=0.05)
             pyautogui.press('enter')
             pyautogui.press('tab')
             pyautogui.press('enter')
             driver.switch_to.window(driver.window_handles[0])
             pyautogui.hotkey('ctrl', '2')
             pyautogui.hotkey('ctrl', 'w')
             pyautogui.hotkey('ctrl', '2')
             pyautogui.hotkey('ctrl', 'w')
             pyautogui.hotkey('ctrl', '1')
         else:
             driver.quit()
             self.output.setText("No Link Found")
         driver.get(d)
     driver.quit()
     if len(self.out) != 0:
         out1 = ""
         for i in self.out:
             out1 = str(out1) + str(i) + ","
         self.output.setText("Error Episodes - " + str(out1))
     else:
         self.output.setText("Downloads Sucessfully Added..")
Ejemplo n.º 53
0
def anpr():
    #tkinter.messagebox.showinfo("Start App", "Press 'i' to start application")
    app = Application().start(r'C:\xampp\htdocs\openalpr\final.exe')
Ejemplo n.º 54
0
 def __init__(self, target):
     self.application = WinApplication(backend="uia").start(target)
     self.main_window = self.application.window(title="Free Address Book")
     self.main_window.wait("visible")
Ejemplo n.º 55
0
from pywinauto.application import Application
import win32gui,os,shutil
dir="H:\云pos安装包"
#杀掉数据库进程
os.system("taskkill /F /IM mysqld.exe")
#root 所指的是当前正在遍历的这个文件夹的本身的地址等价于dir,dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录),files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
for root,dirs,files in os.walk(dir):
    for file in files:
       print(os.path.join(root,file))
    real_path=input("请输入卸载版本路径:")
    app = Application().start(real_path)
    window_title='安装 云POS'
    window_class='WixStdBA'
    ss=win32gui.FindWindow(window_class, window_title)
    app = Application().connect(handle=ss)
    dlg_spec=app.window(title='安装 云POS')
    dlg_spec.window(title='卸载').Click()
    dlg_spec.window(title='关闭').wait('ready',timeout=90)
    dlg_spec.window(title='关闭').Click()
Path='H:\POSsystem'
shutil.rmtree(Path)
print(Path+" clean success!")
Ejemplo n.º 56
0
    while True:
        if keyboard.is_pressed('['): execute = True
        elif keyboard.is_pressed(']'): execute = False
        if execute: mammonite(actuator)
        sleep(0.05)
    """

from pywinauto.application import Application
from time import sleep

(w, h) = (1920, 1080)
var = 0.15
cooldown = 15
process_id = int(input("Enter PID: "))
def clicks():
    wrapper.click_input(coords=(int(0.50 * w), int(0.50 * h)))
    wrapper.click_input(coords=(int((0.50 - var) * w), int(0.50 * h)))
    #wrapper.click_input(coords=(int((0.50 - var) * w), int((0.50 - var) * h)))
    wrapper.click_input(coords=(int(0.50 * w), int((0.50 - var) * h)))
    #wrapper.click_input(coords=(int((0.50 + var) * w), int((0.50 - var) * h)))
    wrapper.click_input(coords=(int((0.50 + var) * w), int(0.50 * h)))
    #wrapper.click_input(coords=(int((0.50 + var) * w), int((0.50 + var) * h)))
    wrapper.click_input(coords=(int(0.50 * w), int((0.50 + var) * h)))
    #wrapper.click_input(coords=(int((0.50 - var) * w), int((0.50 + var) * h)))
    wrapper.minimize()

app = Application().connect(process=process_id)
wrapper = app.window().wrapper_object()
while(True):
    clicks()
    sleep(cooldown)
Ejemplo n.º 57
0
 def __init__(self):
     self.filter_app = Application().connect(path = r"C:\Program Files (x86)\Fianium\SuperChrome\SuperChromeTest.exe")
     self.filter_diag = self.filter_app.TestDualVariableFilter
Ejemplo n.º 58
0
 def setUp(self):
     self.app = Application()
     self.app.start(_test_app())
     self.dlg = self.app.mousebuttons
def main():
    global window_name, refresh_rate

    print('Starting Automatic Refresh Script')

    # Parse arguments from cmd
    parser = argparse.ArgumentParser()
    parser.add_argument("workbook", help="Path to .pbix file")
    parser.add_argument(
        "--workspace",
        help="name of online Power BI service work space to publish in",
        default="My workspace")
    parser.add_argument("--refresh-timeout",
                        help="refresh timeout",
                        default=30000)
    parser.add_argument("--no-publish",
                        dest='publish',
                        help="don't publish, just save",
                        default=True,
                        action='store_false')
    parser.add_argument("--init-wait",
                        help="initial wait time on startup",
                        default=15)
    args = parser.parse_args()

    load_settings()

    timings.after_clickinput_wait = 1
    WORKBOOK = args.workbook
    INIT_WAIT = args.init_wait

    # Kill running PBI
    PROCNAME = "PBIDesktop.exe"
    for proc in psutil.process_iter():
        # check whether the process name matches
        if proc.name() == PROCNAME:
            proc.kill()
    time.sleep(3)

    print("\nStarting Power BI")

    os.system('start "" "' + WORKBOOK + '"')
    time.sleep(INIT_WAIT)

    print("Identifying Power BI window")

    app = Application(backend='uia').connect(path=PROCNAME)
    win = app.window(title_re='.*' + window_name)

    time.sleep(5)

    win.wait("enabled", timeout=300)
    win.Save.wait("enabled", timeout=300)
    win.set_focus()
    win.Home.click_input()
    win.Save.wait("enabled", timeout=300)
    win.wait("enabled", timeout=300)

    print('Refreshing ' + window_name + ' every ' + refresh_rate + ' seconds')
    rate = int(refresh_rate)

    while True:
        win.set_focus()
        win.Refresh.click_input()
        win.Refresh.click_input()
        win.Refresh.click_input()

        win.wait("enabled", timeout=300)

        now = datetime.datetime.now()
        now_plus_refresh_rate = now + datetime.timedelta(seconds=rate)
        print('Next refresh will occur on ' + str(now_plus_refresh_rate))

        time.sleep(rate)
Ejemplo n.º 60
0
# coding: utf-8
from pywinauto.application import Application
import time

app = Application().start("notepad.exe")
app.UntitledNotepad.menu_select("도움말->메모장 정보")
# time.sleep(1) #없어도 충분히 기다림
app['메모장 정보'].확인.click()
app.UntitledNotepad.Edit.type_keys("동작하네", with_spaces=True)