Advertisement
famansour

Tips&Tricks #Retrieve the status of keyboard and mouse buttons in the background

Aug 25th, 2020 (edited)
3,266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # -------------------------------------------
  2. # (c) 2020 Fouad AMANSOUR fd.amansour@gmail.com
  3. # This code can retrieve the status (whether a key is up or down)
  4. # of keyboard and mouse buttons using Virtual-Key Codes in the background
  5. # Replace 0x04 in win32api.GetKeyState(0x04) everywhere in the file
  6. # with Virtual-Key Code of the button for which you want to retrieve the status
  7. # -------------------------------------------
  8.  
  9. import win32api
  10. import time
  11.  
  12. CurrentKeyState = win32api.GetKeyState(0x04)  # "0x04" is the Virtual-Key Code of the Middle mouse button (VK_MBUTTON)
  13.  
  14. while True:
  15.     NewKeyState = win32api.GetKeyState(0x04)
  16.  
  17.     if NewKeyState != CurrentKeyState:  # Button state changed
  18.  
  19.         """
  20.        WHEN THE BUTTON IN QUESTION IS :
  21.        * pressed the 1st time: the value of win32api.GetKeyState() is -128
  22.        * Releases the 1st time: the value of win32api.GetKeyState() is 0
  23.        * pressed the 2nd time: the value of win32api.GetKeyState() is -127
  24.        * Releases the 2nd time: the value of win32api.GetKeyState() is 1      
  25.        """
  26.         if NewKeyState < 0:  # KeyState = -127 or -128
  27.             print('BUTTON PRESSED ---', 'NewKeyState = ', NewKeyState )
  28.  
  29.         else:                # KeyState =1 or 0
  30.             print('BUTTON RELEASED ---', 'NewKeyState = ', NewKeyState)
  31.  
  32.         CurrentKeyState = NewKeyState
  33.        
  34.     time.sleep(0.001)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement