python realizes keyboard control mouse movement

  • 2021-01-02 21:56:52
  • OfStack

When playing QQ billiard game, sometimes it is hard to use the mouse to control the tiny movement of the mouse pointer, so I want to write a program, you can use the keyboard keys up, down, or left to control the mouse movement, only one pixel at a time.

This script relies on the pywin32, pyHook, and pymouse libraries. Please install them yourself. pythoncom is part of the pywin32 library. After running the script, you can control the mouse movement by using the keyboard's upper, lower, or left keys.


# -*- coding:utf-8 -*-
#  On the left 37  on 38  right 39  Under the 40
 
import pythoncom
import pyHook
from pymouse import PyMouse
 
def onKeyboardEvent(event):
 #  Gets the keys pressed id
 keyID = event.KeyID 
 #  Gets the coordinates of the current mouse 
 mouse = PyMouse()
 x, y = mouse.position()
 x = int(x)
 y = int(y)
 
 #  set x and y The offset 
 deltaX = 0
 deltaY = 0
 
 if keyID == 37:
  deltaX = -1
 elif keyID == 38:
  deltaY = -1
 elif keyID == 39:
  deltaX = 1
 elif keyID == 40:
  deltaY = 1
 else:
  return True
 
 #  Move the mouse 
 mouse.move(x + deltaX, y + deltaY)
 return True
 
def main():
 #  Start listening for keyboard events 
 hm = pyHook.HookManager()
 hm.KeyDown = onKeyboardEvent
 hm.HookKeyboard()
 pythoncom.PumpMessages()
 
if __name__ == '__main__':
 main()

Related articles: