Python USES pyhook to monitor keyboards and switch songs

  • 2020-04-02 13:53:38
  • OfStack

When playing dota, I sometimes like to listen to music while playing the game, but I have to cut out the game when switching to the next song, and the hot key of switching to music, CTRL + Alt + direction key, is useless in the game, good thing is painful, today try to use python to achieve keyboard monitoring switch to the next song, the following is posted code


import pythoncom, pyHook
import win32gui,win32api,win32con
 
Lcontrol_press = False
Lmenu_press = False
Left_press = False
 
def OnKeyboardEvent(event):
  global Lcontrol_press # When using global variables in a function, add them global The keyword 
  global Lmenu_press # Or you'll make a mistake 
  global Left_press
  print 'Key:', event.Key
  if (event.Key == "Lcontrol"):
    Lcontrol_press = True
  elif(event.Key == "Lmenu"):
    Lmenu_press = True
  elif(event.Key == "Left"):
    Left_press =True
  handel_key()
  return True
def handel_key() :
  global Lcontrol_press
  global Lmenu_press
  global Left_press  
  if(Lcontrol_press and Lmenu_press and Left_press):
    win32api.keybd_event( 0xB0,win32con.VK_MEDIA_NEXT_TRACK,0,0)
    Lcontrol_press = False
    Lmenu_press = False
    Left_press = False
     
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

Ok, set your player to play at random and press CTRL + Alt + left to switch music while playing (CTRL and Alt are also left)
By the way, those three shortcuts are not a combination of keys, which means that you should first press CTRL and then release, then press Alt and finally press the direction key to switch music.


Related articles: