John5617

Detecting both mouse buttons held down

Jan 25th, 2021 (edited)
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. # full code in answer to:
  2. # https://stackoverflow.com/questions/65889957/detecting-both-mouse-buttons-held-down/65890425#65890425
  3.  
  4. from pynput import mouse
  5.  
  6. global leftPressed, rightPressed, bothPressed
  7. leftPressed = False
  8. rightPressed = False
  9. bothPressed = False
  10.  
  11. # This function will be called when any key of mouse is pressed
  12.  
  13. def on_click(*args):
  14.     global leftPressed, rightPressed, bothPressed
  15.    
  16.     #print(args)
  17.    
  18.     if args[-1]:
  19.         # mouse key pressed
  20.         print('The "{}" mouse key has held down'.format(args[-2].name))
  21.        
  22.         if args[-2].name == "left":
  23.             leftPressed = True
  24.         elif args[-2].name == "right":
  25.             rightPressed = True
  26.            
  27.         if leftPressed and rightPressed:
  28.             # if both left and right are pressed
  29.             bothPressed = True
  30.         print(bothPressed)
  31.  
  32.     elif not args[-1]:
  33.         # mouse key released
  34.         print('The "{}" mouse key is released'.format(args[-2].name))
  35.        
  36.         if args[-2].name == "left":
  37.             leftPressed = False
  38.         elif args[-2].name == "right":
  39.             rightPressed = False
  40.  
  41.         # as one key has been released, both are no longer pressed
  42.         bothPressed = False
  43.         print(bothPressed)
  44.  
  45. # Open Listener for mouse key presses
  46. with mouse.Listener(on_click=on_click) as listener:
  47.     # Listen to the mouse key presses
  48.     listener.join()
  49.  
Add Comment
Please, Sign In to add comment