Mouse control

You can use PyWin32 to locate or move the mouse cursor.

It’s also simple to click, drag, and more


Get mouse cursor position

import win32api

pos = win32api.GetCursorPos()
print(pos)

GetCursorPos() in the win32api module returns the current position of the mouse cursor in the form of the tuple (x, y).


Move mouse cursor

import win32api

pos = (200, 200)
win32api.SetCursorPos(pos)

SetCursorPos() method moves the position of the mouse cursor to the position of the input tuple (x, y).


Click button

import win32api
import win32con


def mouse_click(x, y):
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)


mouse_click(300, 300)

win32con is a module with various constants related to the Win32 API.

Created one mouse_click(x, y) function. First, use SetCursorPos((x, y)) to move the cursor to the position of (x, y).

Insert constants for mouse action and click in the first parameter of mouse_event() .

If you enter win32con.MOUSEEVENTF_LEFTDOWN , the left button is pressed; if you enter win32con.MOUSEEVENTF_LEFTUP , the button is released.

For the second and third parameters, enter the x, y positions where the mouse event will be performed.

More information about the mouse_event() function can be found at the following link: mouse_event() function.

As a result, the mouse cursor moves to the position (x, y) = (300, 300) and click the left button once via mouse_click(300, 300) .

Prev/Next