Search code examples
pythonmousemouselistener

Python - get raw mouse input


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.


Solution

  • 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()