Search code examples
pythonpython-3.xcursor-position

Take action when the cursor position crosses a particular x value


Here is my situation

import win32api

while True:
    x,y = win32api.GetCursorPos()
    if x < 0:
        print("2")
    else:
        print("1")

This constantly prints '1' or '2' depending on the x co-ordinate of the mouse being less than 0 (dual monitors, RHS is primary so < 0 means mouse is on second monitor). How can I make it only print one instance of the string '1' or '2' when x becomes < 0 or x becomes >= 0?


Solution

  • You need to remember the last state printed so that you can detect when a new state is entered.

    last_state = False
    while True:
        x,y = win32api.GetCursorPos()
        state = x < 0
        if state == last_state:
            continue
        last_state = state
        if state:
            print("2")
        else:
            print("1")