49

Is it possible to get the overall cursor position in Windows using the standard Python libraries?

martineau
  • 119,623
  • 25
  • 170
  • 301
rectangletangle
  • 50,393
  • 94
  • 205
  • 275
  • 2
    For a question that asks that this be done using standard Python libraries, there isn't actually a solution. The chosen answer requires you install additional modules. I'm just saying this because googling the question points straight to here. (You CAN use tkinter, but it requires that you have an instance(?) of tkinter running at the same time AFAIK) – Micrified Jul 04 '14 at 05:45
  • 2
    It's depressing to see that 99% of programming population seem to think that *`"cursor position"`* is the same thing as *mouse/pointer position*, when nothing can be further from [the truth](https://en.wikipedia.org/wiki/Cursor_(user_interface)). In this OP, user is asking for the "text" position, not the graphical *(x,y) coordinates* of the pointer. – not2qubit Jan 15 '22 at 13:32
  • Right! It is very depressing. But not so because people assume what you say, but mainly because they don't even see or undestand that the question asks for **TEXT** cursor position!!! And the poster doesn't even care about that. He most probably forgot what was the question he himself asked! – Apostolos Aug 14 '22 at 11:15

13 Answers13

61

Using the standard ctypes library, this should yield the current on screen mouse coordinates without any third party modules:

from ctypes import windll, Structure, c_long, byref


class POINT(Structure):
    _fields_ = [("x", c_long), ("y", c_long)]



def queryMousePosition():
    pt = POINT()
    windll.user32.GetCursorPos(byref(pt))
    return { "x": pt.x, "y": pt.y}


pos = queryMousePosition()
print(pos)

I should mention that this code was taken from an example found here So credit goes to Nullege.com for this solution.

Micrified
  • 3,338
  • 4
  • 33
  • 59
  • 2
    Bahaha, just found that same snippet at Nullege when I was researching this. But this should be the accepted answer as it doesn't use 3rd party code and it works like a charm. – RattleyCooper Apr 01 '16 at 20:13
  • 3
    I made a fix to this, since it causes a bug that people might not notice immediately: cursor positions are signed, not unsigned, and can be negative if the mouse is on a monitor to the left of the primary one. With "c_ulong", you end up getting coordinates like 4294967196 instead of -100. (It can happen vertically too, but it's less common.) – Glenn Maynard Jul 07 '17 at 07:33
  • a comment about what happens in this code step by step? – Siemkowski Dec 07 '17 at 17:25
34
win32gui.GetCursorPos(point)

This retrieves the cursor's position, in screen coordinates - point = (x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()

Retrieves information about the global cursor.

Links:

I am assuming that you would be using python win32 API bindings or pywin32.

pyfunc
  • 65,343
  • 15
  • 148
  • 136
15

You will not find such function in standard Python libraries, while this function is Windows specific. However if you use ActiveState Python, or just install win32api module to standard Python Windows installation you can use:

x, y = win32api.GetCursorPos()
Michał Niklas
  • 53,067
  • 18
  • 70
  • 114
8

Using pyautogui

To install

pip install pyautogui

and to find the location of the mouse pointer

import pyautogui
print(pyautogui.position())

This will give the pixel location to which mouse pointer is at.

Abhinav
  • 81
  • 1
  • 4
7

I found a way to do it that doesn't depend on non-standard libraries!

Found this in Tkinter

self.winfo_pointerxy()
rectangletangle
  • 50,393
  • 94
  • 205
  • 275
6

For Mac using native library:

import Quartz as q
q.NSEvent.mouseLocation()

#x and y individually
q.NSEvent.mouseLocation().x
q.NSEvent.mouseLocation().y

If the Quartz-wrapper is not installed:

python3 -m pip install -U pyobjc-framework-Quartz

(The question specify Windows, but a lot of Mac users come here because of the title)

Punnerud
  • 7,195
  • 2
  • 54
  • 44
5

It's possible, and not even that messy! Just use:

from ctypes import windll, wintypes, byref

def get_cursor_pos():
    cursor = wintypes.POINT()
    windll.user32.GetCursorPos(byref(cursor))
    return (cursor.x, cursor.y)

The answer using pyautogui made me wonder how that module was doing it, so I looked and this is how.

lazy juice
  • 59
  • 1
  • 1
  • This doesn't give the *cursor position* as you think. It gives the **screen** *(x,y) coordinates* of the **mouse pointer**. Check with: `while(1): print('{}\t\t\r'.format(get_cursor_pos()), end='')` – not2qubit Jan 15 '22 at 13:40
4

This could be a possible code for your problem :

# Note you  need to install PyAutoGUI for it to work


import pyautogui
w = pyautogui.position()
x_mouse = w.x
y_mouse = w.y
print(x_mouse, y_mouse)
Zig Razor
  • 3,381
  • 2
  • 15
  • 35
  • Using `pyautogui.position()` was already answered [here](https://stackoverflow.com/a/60278875/2745495) and [here](https://stackoverflow.com/a/62676704/2745495) – Gino Mempin Oct 23 '20 at 02:37
3

Prerequisites

Install Tkinter. I've included the win32api for as a Windows-only solution.

Script

#!/usr/bin/env python

"""Get the current mouse position."""

import logging
import sys

logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                    level=logging.DEBUG,
                    stream=sys.stdout)


def get_mouse_position():
    """
    Get the current position of the mouse.

    Returns
    -------
    dict :
        With keys 'x' and 'y'
    """
    mouse_position = None
    import sys
    if sys.platform in ['linux', 'linux2']:
        pass
    elif sys.platform == 'Windows':
        try:
            import win32api
        except ImportError:
            logging.info("win32api not installed")
            win32api = None
        if win32api is not None:
            x, y = win32api.GetCursorPos()
            mouse_position = {'x': x, 'y': y}
    elif sys.platform == 'Mac':
        pass
    else:
        try:
            import Tkinter  # Tkinter could be supported by all systems
        except ImportError:
            logging.info("Tkinter not installed")
            Tkinter = None
        if Tkinter is not None:
            p = Tkinter.Tk()
            x, y = p.winfo_pointerxy()
            mouse_position = {'x': x, 'y': y}
        print("sys.platform={platform} is unknown. Please report."
              .format(platform=sys.platform))
        print(sys.version)
    return mouse_position

print(get_mouse_position())
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
2
sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()

Or with one-liner from the command line:

python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)
jturi
  • 1,615
  • 15
  • 11
2

I know this is an old thread, but have been having hard time figuring out how to do this with JUST the python standard libraries.

I think the code below will work to get the cursor position in a windows terminal:

import sys
import msvcrt

print('ABCDEF',end='')
sys.stdout.write("\x1b[6n")
sys.stdout.flush()
buffer = bytes()
while msvcrt.kbhit():
    buffer += msvcrt.getch()
hex_loc = buffer.decode()
hex_loc = hex_loc.replace('\x1b[','').replace('R','')
token = hex_loc.split(';')
print(f'  Row: {token[0]}  Col: {token[1]}')
user996306
  • 21
  • 2
1

Use pygame

import pygame

mouse_pos = pygame.mouse.get_pos()

This returns the x and y position of the mouse.

See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos

Michael Wang
  • 145
  • 11
  • This returns a tuple (-1,-1) !! (After you initialize pygame, of course, which is missing here!) This is a strong downvote case but I don't like and never do this, unlike many other people. I prefer writing comments. It's more helpful. – Apostolos Jan 04 '20 at 09:47
1

If you're doing automation and want to get coordinates of where to click, simplest and shortest approach would be:

import pyautogui

while True:
    print(pyautogui.position())

This will track your mouse position and would keep on printing coordinates.

Mujeeb Ishaque
  • 2,259
  • 24
  • 16