当前位置:Gxlcms > Python > python使用pyhook监控键盘并实现切换歌曲的功能

python使用pyhook监控键盘并实现切换歌曲的功能

时间:2021-07-01 10:21:17 帮助过:60人阅读

自己在玩dota的时候有时候喜欢边玩游戏边听音乐,但是切换下一曲的时候必须得切出游戏,而切换音乐的热键ctrl+alt+方向键在游戏的时候没有用,好事蛋疼,今天试试使用python来实现键盘监控切换下一曲,下面贴出代码

  1. import pythoncom, pyHook
  2. import win32gui,win32api,win32con
  3. Lcontrol_press = False
  4. Lmenu_press = False
  5. Left_press = False
  6. def OnKeyboardEvent(event):
  7. global Lcontrol_press #在函数里面使用全局变量的时候要加上global关键字
  8. global Lmenu_press #要不然会出错
  9. global Left_press
  10. print 'Key:', event.Key
  11. if (event.Key == "Lcontrol"):
  12. Lcontrol_press = True
  13. elif(event.Key == "Lmenu"):
  14. Lmenu_press = True
  15. elif(event.Key == "Left"):
  16. Left_press =True
  17. handel_key()
  18. return True
  19. def handel_key() :
  20. global Lcontrol_press
  21. global Lmenu_press
  22. global Left_press
  23. if(Lcontrol_press and Lmenu_press and Left_press):
  24. win32api.keybd_event( 0xB0,win32con.VK_MEDIA_NEXT_TRACK,0,0)
  25. Lcontrol_press = False
  26. Lmenu_press = False
  27. Left_press = False
  28. hm = pyHook.HookManager()
  29. hm.KeyDown = OnKeyboardEvent
  30. hm.HookKeyboard()
  31. pythoncom.PumpMessages()

好了,把你的播放器设置为随机播放就可以在游戏的时候按下ctrl+alt+左方向键就可以切换音乐啦(ctrl和alt也是左边的)
顺便说明下,那三个快捷键不是组合键,意思是你要先按下ctrl然后放开,在按下alt,最后按一下做方向键就切换音乐了.这三个键的顺序不能按错.

人气教程排行