Python win32api.GetCursorPos() Examples

The following are 13 code examples of win32api.GetCursorPos(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32api , or try the search function .
Example #1
Source File: steam.py    From Yugioh-bot with MIT License 14 votes vote down vote up
def tap(self, x, y):
        if self.run_time.stop:
            return
        x, y = int(x), int(y)
        self.root.debug("Tapping at location ({},{})".format(x, y))
        if self._debug:
            # Helper to debug taps
            input("waiting for confirmation press enter")
        ox, oy = win32api.GetCursorPos()
        curr_window = win32gui.GetForegroundWindow()
        win32gui.ShowWindow(self.win_handle, win32con.SW_RESTORE)
        x, y = int(x), int(y)
        cx, cy = win32gui.ClientToScreen(self.win_handle, (x, y))
        x, y = self.__calculate_absolute_coordinates__(cx, cy)
        win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE,
                             x, y, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
        time.sleep(20 / 1000)
        win32api.SetCursorPos((ox, oy))
        win32gui.SetActiveWindow(curr_window) 
Example #2
Source File: regedit.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def OnItemRightClick(self, notify_data, extra):
		# First select the item we right-clicked on.
		pt = self.ScreenToClient(win32api.GetCursorPos())
		flags, hItem = self.HitTest(pt)
		if hItem==0 or commctrl.TVHT_ONITEM & flags==0:
			return None
		self.Select(hItem, commctrl.TVGN_CARET)

		menu = win32ui.CreatePopupMenu()
		menu.AppendMenu(win32con.MF_STRING|win32con.MF_ENABLED,1000, "Add Key")
		menu.AppendMenu(win32con.MF_STRING|win32con.MF_ENABLED,1001, "Add Value")
		menu.AppendMenu(win32con.MF_STRING|win32con.MF_ENABLED,1002, "Delete Key")
		self.HookCommand(self.OnAddKey, 1000)
		self.HookCommand(self.OnAddValue, 1001)
		self.HookCommand(self.OnDeleteKey, 1002)
		menu.TrackPopupMenu(win32api.GetCursorPos()) # track at mouse position.
		return None 
Example #3
Source File: pattern_generator.py    From ultra_secret_scripts with GNU General Public License v3.0 5 votes vote down vote up
def main():
    running = True
    reading_clicks = False
    file = open("tracked_pattern.txt", "w")
    prev_x = 0
    prev_y = 0
    while running:
        if win32api.GetAsyncKeyState(F4):
            reading_clicks = not reading_clicks
            print("Reading clicks: {}".format(reading_clicks))
            time.sleep(0.2)

        if win32api.GetAsyncKeyState(F10):
            running = not running
            time.sleep(0.2)

        if win32api.GetAsyncKeyState(LMB) < 0 and reading_clicks:
            beep()
            now_pos = win32api.GetCursorPos()
            if prev_x == 0 and prev_y == 0:
                prev_x = now_pos[0]
                prev_y = now_pos[1]
                moved_x = 0
                moved_y = 0
            else:
                moved_x = int((now_pos[0]-prev_x+1)/2)  # div by 2 round up => real pattern
                moved_y = int((now_pos[1]-prev_y+1)/2)  # because you should click x2 zoomed pattern
                prev_x = now_pos[0]
                prev_y = now_pos[1]

            formatted = "[{}, {}],".format(moved_x, moved_y)
            print(formatted)
            file.write("{}\n".format(formatted))
            time.sleep(0.15)
        time.sleep(0.1)

    print("Saving new pattern to tracked_pattern.txt")
    file.close() 
Example #4
Source File: debugger.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def OnItemRightClick(self, notify_data, extra):
		# First select the item we right-clicked on.
		pt = self.ScreenToClient(win32api.GetCursorPos())
		flags, hItem, subitem = self.HitTest(pt)
		if hItem==-1 or commctrl.TVHT_ONITEM & flags==0:
			return None
		self.SetItemState(hItem, commctrl.LVIS_SELECTED, commctrl.LVIS_SELECTED)

		menu = win32ui.CreatePopupMenu()
		menu.AppendMenu(win32con.MF_STRING|win32con.MF_ENABLED,1000, "Edit item")
		menu.AppendMenu(win32con.MF_STRING|win32con.MF_ENABLED,1001, "Delete item")
		dockbar = self.GetParent()
		if dockbar.IsFloating():
			hook_parent = win32ui.GetMainFrame()
		else:
			hook_parent = self.GetParentFrame()
		hook_parent.HookCommand(self.OnEditItem, 1000)
		hook_parent.HookCommand(self.OnDeleteItem, 1001)
		menu.TrackPopupMenu(win32api.GetCursorPos()) # track at mouse position.
		return None 
Example #5
Source File: test_win.py    From Airtest with Apache License 2.0 5 votes vote down vote up
def test_mouse_move(self):
        self.windows.mouse_move((100, 100))
        self.assertTupleEqual(win32api.GetCursorPos(), (100, 100))
        self.windows.mouse_move((150, 50))
        self.assertTupleEqual(win32api.GetCursorPos(), (150, 50)) 
Example #6
Source File: win.py    From Airtest with Apache License 2.0 5 votes vote down vote up
def mouse_down(self, button='left'):
        """Simulates a `mousedown` event.

        :param button: A string indicating which mouse button to be pressed.
                       Available mouse button options are:
                       {'left', 'middle', 'right'}.
        """
        buttons = {'left', 'middle', 'right'}
        if not isinstance(button, str) or button not in buttons:
            raise ValueError('invalid literal for mouse_down(): {}'.format(button))
        else:
            coords = self._action_pos(win32api.GetCursorPos())
            self.mouse.press(button=button, coords=coords) 
Example #7
Source File: win.py    From Airtest with Apache License 2.0 5 votes vote down vote up
def mouse_up(self, button='left'):
        """Simulates a `mouseup` event.

        A call to the mouse_up() method usually follows a call to the
        mouse_down() method of the same mouse button.

        :param button: A string indicating which mouse button to be released.
        """
        buttons = {'left', 'middle', 'right'}
        if not isinstance(button, str) or button not in buttons:
            raise ValueError('invalid literal for mouse_up(): {}'.format(button))
        else:
            coords = self._action_pos(win32api.GetCursorPos())
            self.mouse.release(button=button, coords=coords) 
Example #8
Source File: tray_worker.py    From attack_monitor with GNU General Public License v3.0 5 votes vote down vote up
def get_cursor_position(self):
        while(True):
            try:
                savedpos = win32api.GetCursorPos()
                return savedpos
            except pywintypes.error:
                time.sleep(1) 
Example #9
Source File: main.py    From MouseTracks with GNU General Public License v3.0 5 votes vote down vote up
def get_cursor_pos():
    """Read the cursor position on screen.
    Returns:
        (x, y) coordinates as a tuple.
        None if it can't be detected.
    """
    try:
        return win32api.GetCursorPos()
    except win32api.error:
        return None 
Example #10
Source File: shell_view.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def OnContextMenu(self, hwnd, msg, wparam, lparam):
        # Get the selected items.
        pidls = []
        n = -1
        while 1:
            n = win32gui.SendMessage(self.hwnd_child,
                                     commctrl.LVM_GETNEXTITEM,
                                     n,
                                     commctrl.LVNI_SELECTED)
            if n==-1:
                break
            pidls.append(self.children[n][-1:])
        
        spt = win32api.GetCursorPos()
        if not pidls:
            print "Ignoring background click"
            return
        # Get the IContextMenu for the items.
        inout, cm = self.folder.GetUIObjectOf(self.hwnd_parent, pidls, shell.IID_IContextMenu, 0)
        hmenu = win32gui.CreatePopupMenu()
        sel = None
        # As per 'Q179911', we need to determine if the default operation
        # should be 'open' or 'explore'
        try:
            flags = 0
            try:
                self.browser.GetControlWindow(shellcon.FCW_TREE)
                flags |= shellcon.CMF_EXPLORE
            except pythoncom.com_error:
                pass
            id_cmd_first = 1 # TrackPopupMenu makes it hard to use 0
            cm.QueryContextMenu(hmenu, 0, id_cmd_first, -1, flags)
            tpm_flags = win32con.TPM_LEFTALIGN | win32con.TPM_RETURNCMD | \
                        win32con.TPM_RIGHTBUTTON
            sel = win32gui.TrackPopupMenu(hmenu,
                                          tpm_flags,
                                          spt[0], spt[1],
                                          0, self.hwnd, None)
            print "TrackPopupMenu returned", sel
        finally:
            win32gui.DestroyMenu(hmenu)
        if sel:
            ci = 0, self.hwnd_parent, sel-id_cmd_first, None, None, 0, 0, 0
            cm.InvokeCommand(ci) 
Example #11
Source File: DockingBar.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def CalcDynamicLayout(self, length, mode):
		# Support for diagonal sizing.
		if self.IsFloating():
			self.GetParent().GetParent().ModifyStyle(win32ui.MFS_4THICKFRAME, 0)
		if mode & (win32ui.LM_HORZDOCK | win32ui.LM_VERTDOCK):
			flags = win32con.SWP_NOSIZE | win32con.SWP_NOMOVE | win32con.SWP_NOZORDER |\
				win32con.SWP_NOACTIVATE | win32con.SWP_FRAMECHANGED
			self.SetWindowPos(0, (0, 0, 0, 0,), flags)
			self.dockSite.RecalcLayout()
			return self._obj_.CalcDynamicLayout(length, mode)

		if mode & win32ui.LM_MRUWIDTH:
			return self.sizeFloat
		if mode & win32ui.LM_COMMIT:
			self.sizeFloat = length, self.sizeFloat[1]
			return self.sizeFloat
		# More diagonal sizing.
		if self.IsFloating():
			dc = self.dockContext
			pt = win32api.GetCursorPos()
			windowRect = self.GetParent().GetParent().GetWindowRect()

			hittest = dc.nHitTest
			if hittest==win32con.HTTOPLEFT:
				cx = max(windowRect[2] - pt[0], self.cMinWidth) - self.cxBorder
				cy = max(windowRect[3] - self.cCaptionSize - pt[1],self.cMinHeight) - 1
				self.sizeFloat = cx, cy

				top = min(pt[1], windowRect[3] - self.cCaptionSize - self.cMinHeight) - self.cyBorder
				left = min(pt[0], windowRect[2] - self.cMinWidth) - 1
				dc.rectFrameDragHorz = left, top, dc.rectFrameDragHorz[2], dc.rectFrameDragHorz[3]
				return self.sizeFloat
			if hittest==win32con.HTTOPRIGHT:
				cx = max(pt[0] - windowRect[0], self.cMinWidth)
				cy = max(windowRect[3] - self.cCaptionSize - pt[1], self.cMinHeight) - 1
				self.sizeFloat = cx, cy

				top = min(pt[1], windowRect[3] - self.cCaptionSize - self.cMinHeight) - self.cyBorder
				dc.rectFrameDragHorz = dc.rectFrameDragHorz[0], top, dc.rectFrameDragHorz[2], dc.rectFrameDragHorz[3]
				return self.sizeFloat

			if hittest==win32con.HTBOTTOMLEFT:
				cx = max(windowRect[2] - pt[0], self.cMinWidth) - self.cxBorder
				cy = max(pt[1] - windowRect[1] - self.cCaptionSize, self.cMinHeight)
				self.sizeFloat = cx, cy

				left = min(pt[0], windowRect[2] -self.cMinWidth) - 1
				dc.rectFrameDragHorz = left, dc.rectFrameDragHorz[1], dc.rectFrameDragHorz[2], dc.rectFrameDragHorz[3]
				return self.sizeFloat

			if hittest==win32con.HTBOTTOMRIGHT:
				cx = max(pt[0] - windowRect[0], self.cMinWidth)
				cy = max(pt[1] - windowRect[1] - self.cCaptionSize, self.cMinHeight)
				self.sizeFloat = cx, cy
				return self.sizeFloat

		if mode & win32ui.LM_LENGTHY:
			self.sizeFloat = self.sizeFloat[0], max(self.sizeMin[1], length)
			return self.sizeFloat
		else:
			return max(self.sizeMin[0], length), self.sizeFloat[1] 
Example #12
Source File: win.py    From Airtest with Apache License 2.0 4 votes vote down vote up
def touch(self, pos, **kwargs):
        """
        Perform mouse click action

        References:
            https://pywinauto.readthedocs.io/en/latest/code/pywinauto.mouse.html

        Args:
            pos: coordinates where to click
            **kwargs: optional arguments

        Returns:
            None

        """
        duration = kwargs.get("duration", 0.01)
        right_click = kwargs.get("right_click", False)
        button = "right" if right_click else "left"
        steps = kwargs.get("steps", 1)
        offset = kwargs.get("offset", 0)

        start = self._action_pos(win32api.GetCursorPos())
        end = self._action_pos(pos)
        start_x, start_y = self._fix_op_pos(start)
        end_x, end_y = self._fix_op_pos(end)

        interval = float(duration) / steps
        time.sleep(interval)

        for i in range(1, steps):
            x = int(start_x + (end_x-start_x) * i / steps)
            y = int(start_y + (end_y-start_y) * i / steps)
            self.mouse.move(coords=(x, y))
            time.sleep(interval)

        self.mouse.move(coords=(end_x, end_y))

        for i in range(1, offset+1):
            self.mouse.move(coords=(end_x+i, end_y+i))
            time.sleep(0.01)

        for i in range(offset):
            self.mouse.move(coords=(end_x+offset-i, end_y+offset-i))
            time.sleep(0.01)

        self.mouse.press(button=button, coords=(end_x, end_y))
        time.sleep(duration)
        self.mouse.release(button=button, coords=(end_x, end_y)) 
Example #13
Source File: shell_view.py    From Email_My_PC with MIT License 4 votes vote down vote up
def OnContextMenu(self, hwnd, msg, wparam, lparam):
        # Get the selected items.
        pidls = []
        n = -1
        while 1:
            n = win32gui.SendMessage(self.hwnd_child,
                                     commctrl.LVM_GETNEXTITEM,
                                     n,
                                     commctrl.LVNI_SELECTED)
            if n==-1:
                break
            pidls.append(self.children[n][-1:])
        
        spt = win32api.GetCursorPos()
        if not pidls:
            print "Ignoring background click"
            return
        # Get the IContextMenu for the items.
        inout, cm = self.folder.GetUIObjectOf(self.hwnd_parent, pidls, shell.IID_IContextMenu, 0)
        hmenu = win32gui.CreatePopupMenu()
        sel = None
        # As per 'Q179911', we need to determine if the default operation
        # should be 'open' or 'explore'
        try:
            flags = 0
            try:
                self.browser.GetControlWindow(shellcon.FCW_TREE)
                flags |= shellcon.CMF_EXPLORE
            except pythoncom.com_error:
                pass
            id_cmd_first = 1 # TrackPopupMenu makes it hard to use 0
            cm.QueryContextMenu(hmenu, 0, id_cmd_first, -1, flags)
            tpm_flags = win32con.TPM_LEFTALIGN | win32con.TPM_RETURNCMD | \
                        win32con.TPM_RIGHTBUTTON
            sel = win32gui.TrackPopupMenu(hmenu,
                                          tpm_flags,
                                          spt[0], spt[1],
                                          0, self.hwnd, None)
            print "TrackPopupMenu returned", sel
        finally:
            win32gui.DestroyMenu(hmenu)
        if sel:
            ci = 0, self.hwnd_parent, sel-id_cmd_first, None, None, 0, 0, 0
            cm.InvokeCommand(ci)