>  기사  >  백엔드 개발  >  python使用pyhook监控键盘并实现切换歌曲的功能

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

WBOY
WBOY원래의
2016-06-17 08:22:191559검색

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

import pythoncom, pyHook
import win32gui,win32api,win32con
 
Lcontrol_press = False
Lmenu_press = False
Left_press = False
 
def OnKeyboardEvent(event):
  global Lcontrol_press #在函数里面使用全局变量的时候要加上global关键字
  global Lmenu_press #要不然会出错
  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()

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.