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


自己在玩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,最后按一下做方向键就切换音乐了.这三个键的顺序不能按错.


python使用pyHookHookManager()返回来的event中,eventTime怎转换成为datetime形式?

我觉得不是时间戳(或者说,不是通常意义下的时间戳)。
这里的event可能是KeyboardEvent或 MouseEvent(视钩子类型而定)。而这两个类又都是HookEvent的子类。
HookEvent有如下几个成员:
Message: Keyboard or mouse event message
Time: Seconds since the epoch when the even current
Window: Window handle of the foreground window at the time of the event
WindowName: Name of the foreground window at the time of the event
这里,对Time成员的描述是:
Seconds since the epoch when the even current

这里的epoch很有意思。
一般上,我们在使用Python中的time模块,或者C标准库中的time.h时,认为epoch是(摘自Python2.7 time模块的文档):
The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the “time since the epoch” is zero. For Unix, the epoch is 1970.
但是,这里的epoch却不是。看下面一段改编自pyhook官网的小例子:
# -*- coding: utf-8 -*-import pythoncom, pyHookimport win32apiimport time def OnKeyboardEvent(event): print event.Time # Return the time in seconds since the epoch as a floating point number. # # The epoch is the point where the time starts. On January 1st of that year, # at 0 hours, the “time since the epoch” is zero. For Unix, the epoch is 1970. print time.time() # Returns the number of milliseconds since windows started print win32api.GetTickCount() print 'MessageName:',event.MessageName print 'Message:',event.Message print 'Time:', time.ctime(time.time()) print 'Window:',event.Window print 'WindowName:',event.WindowName print 'Ascii:', event.Ascii, chr(event.Ascii) print 'Key:', event.Key prin......余下全文>>
 

在python 中怎进行键盘监听?有的资料上说 要用到“钩”这东西 第三方库pywin32 与PyHook 怎用 高人指

给你找了个离子。。

oldj.net/article/python-hook/
 

评论关闭