Python - get raw mouse input

Viewed 2331

I want to use Python to read raw data from the mouse (e.g. left signal, right signal) independent of the mouse pointer. I don't want to read the position of the cursor, I want to read the raw data, akin to how a game would. How can I do that? I can't find any libraries that support it.

I'm using Windows.

Edit: To clarify, when I said "left signal and right signal", I meant mouse movement, not mouse clicks, Edit 2: I believe the terminology is that I want the "mouse delta." This is how people did it in autohotkey - https://www.autohotkey.com/boards/viewtopic.php?t=10159 - but I want it in Python.

Edit 3: I should mention that this is in a game that constantly resets pointer position, so I can't use the difference in pointer position. That's why I want a lower level API.

2 Answers

Get the mouse position and compare two events. If the x-axis value increases, the mouse moved right, if the x-axis value decreases, the mouse moved left:

from pynput.mouse import Listener

last_position = None

def on_move(x, y):
    global last_position
    if last_position:
        if x > last_position:
            print('mouse moved right')
        elif x < last_position:
            print('mouse moved left')
    last_position = x

with Listener(on_move=on_move) as listener:
    listener.join()        

You can always compare the position constantly that would have easily given you a delta. Any lower level API you will have to code a mouse driver yourself, which is what game developers do to prevent people from scripting, which isn't what python made for.

import pyautogui
import time


while True:
    prev_x, prev_y = pyautogui.position()
    time.sleep(0.3)
    curr_x, curr_y = pyautogui.position()
    if (curr_x - prev_x) > 0:
        print("move right")
    else:
        print("move left")
Related