This article describes how to capture and simulate mouse events in Python, and describes how to use the PyHook and PyWin32 modules, for more information about how to capture and simulate mouse events in Python, see the following example. Share it with you for your reference. The specific analysis is as follows:
This holiday has played a lot of galgames, but some very old games do not have an automatic running mode. clicking the mouse is too damaging, so I want to map the scroll mouse wheel to clicking the mouse.
I searched the internet and did not find any ready-made software, and the key-pushing wizard was too heavyweight. so I thought I could write it myself in Python.
Install both PyHook and PyWin32 here (we recommend that you use the exe version to avoid various egresses during installation ).
I flipped through the tutorial and found that the implementation is very simple:
#-*-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 '---' # return True to pass the event to another handler; otherwise, stop the propagation event and return True # create the hook management object hm = pyHook. hookManager () # listens to all mouse events hm. mouseAll = OnMouseEvent # is equivalent to hm. subscribeMouseAll (OnMouseEvent) # start to listen to the mouse event hm. hookMouse () # listen until you manually exit the pythoncom program. pumpMessages ()
In this example, the program captures all the mouse events. In fact, I only need to capture the events that scroll down the scroll wheel. After turning over the document, it corresponds to MouseWheel. then, you only need to determine whether event. Wheel is-1.
The last step is to trigger the mouse click. This requires win32api. mouse_event (), send an event that presses the left mouse button, and then send the event that pops up, and then click it.
The final code is as follows:
# -*- 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()
I hope this article will help you with Python programming.