Python捕捉和模拟鼠标事件的方法
Jun 06, 2016 am 11:18 AM本文实例讲述了Python捕捉和模拟鼠标事件的方法。分享给大家供大家参考。具体分析如下:
这个假期玩了不少galgame,不过有些很老的游戏没有自动运行模式,点击鼠标又太伤按键了,于是想把滚动鼠标滚轮映射为点击鼠标。
网上搜了一下,没发现什么现成的软件,而按键精灵又太重量级了,于是考虑干脆自己用Python写个算了。
这里需要把PyHook和PyWin32都装上(建议下exe版,免得安装时各种蛋疼)。
翻了翻教程,发现实现起来很简单:
# -*- coding: utf-8 -*- import pythoncom, 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 '---' # 返回 True 可将事件传给其它处理程序,否则停止传播事件 return True # 创建钩子管理对象 hm = pyHook.HookManager() # 监听所有鼠标事件 hm.MouseAll = OnMouseEvent # 等效于hm.SubscribeMouseAll(OnMouseEvent) # 开始监听鼠标事件 hm.HookMouse() # 一直监听,直到手动退出程序 pythoncom.PumpMessages()
这个例子程序捕捉了所有的鼠标事件,实际上我只需要捕捉向下滚动滚轮的事件即可。翻了下文档,对应的是MouseWheel,之后只要判断event.Wheel是否为-1即可。
最后就是触发鼠标点击了,这就需要用到win32api.mouse_event()了,发送一个按下鼠标左键的事件,再发送弹起的事件,就完成一次单击了。
最终代码如下:
# -*- coding: utf-8 -*- import pythoncom import pyHook import time import win32api import win32con def onMouseWheel(event): if event.Wheel == -1: win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0) return True hm = pyHook.HookManager() hm.MouseWheel = onMouseWheel hm.HookMouse() pythoncom.PumpMessages()
希望本文所述对大家的Python程序设计有所帮助。

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the advantages and disadvantages of templating?

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step

Share several .NET open source AI and LLM related project frameworks

A complete guide to golang function debugging and analysis
