Search code examples
python-3.xpynput

Listen to mouse and keyboard events using python


i am trying to prompt error massage if the keyboard or mouse is not in used for some chunk of time. for that i tried pynput module, which is not worth for me. can anyone help me for this thing, thank you


Solution

  • This code will print(xxxxx) if you don't move(or click) your mouse and press your keyboard in five seconds.

    from pynput import mouse,keyboard
    import time
    def on_move(x, y):
        global LastTime
        LastTime = time.time()
    
    def on_click(x, y, button, pressed):
        global LastTime
        LastTime = time.time()
    
    def on_scroll(x, y, dx, dy):
        global LastTime
        LastTime = time.time()
    
    def on_press(key):
        global LastTime
        LastTime = time.time()
    
    LastTime = time.time()
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
    listener = mouse.Listener(on_move=on_move,on_click=on_click,on_scroll=on_scroll)
    listener.start()
    while True:
        if time.time()-LastTime >= 5: # the break time,5 is second
            print("You need break your computer")
            LastTime = time.time()