Python2.7: 使用Pyhook模块监听鼠标键盘事件-获取坐标。因该模块对Python3 有兼容性问题,故采用python2.7解释器。
目前创新互联已为1000多家的企业提供了网站建设、域名、虚拟空间、网站托管、服务器托管、企业网站设计、濠江网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。原程序可监听所有事件,现注释掉部分功能,只输出鼠标左键触发的坐标,用于获取坐标,方便自动化取点。
# -*- coding: utf-8 -*- # # import pythoncom import pyHook def onMouseEvent(event): # 监听鼠标事件 # print ("MessageName:", event.MessageName) # print ("Message:", event.Message) # print ("Time:", event.Time) # print ("Window:", event.Window) # print ("WindowName:", event.WindowName) # print ("Position:", event.Position) # print ("Wheel:", event.Wheel) # print ("Injected:", event.Injected) # print ("---") if event.MessageName == 'mouse left down': print 'mouse left down' print ("Position:", event.Position) # 返回 True 以便将事件传给其它处理程序 # 注意,这儿如果返回 False ,则鼠标事件将被全部拦截 # 也就是说你的鼠标看起来会僵在那儿,似乎失去响应了 return True def onKeyboardEvent(event): # 监听键盘事件 # print ("MessageName:", event.MessageName) # print ("Message:", event.Message) # print ("Time:", event.Time) # print ("Window:", event.Window) # print ("WindowName:", event.WindowName) # print ("Ascii:", event.Ascii, chr(event.Ascii)) # print ("Key:", event.Key) # print ("KeyID:", event.KeyID) # print ("ScanCode:", event.ScanCode) # print ("Extended:", event.Extended) # print ("Injected:", event.Injected) # print ("Alt", event.Alt) # print ("Transition", event.Transition) # print ("---") # 同鼠标事件监听函数的返回值 return True def main(): # 创建一个“钩子”管理对象 hm = pyHook.HookManager() # 监听所有键盘事件 #hm.KeyDown = onKeyboardEvent # 设置键盘“钩子” #hm.HookKeyboard() # 监听所有鼠标事件 hm.MouseAll = onMouseEvent # 设置鼠标“钩子” hm.HookMouse() # 进入循环,如不手动关闭,程序将一直处于监听状态 pythoncom.PumpMessages() if __name__ == "__main__": main()