SoFunction
Updated on 2024-11-12

python implement keyboard control mouse movement

When playing QQ Pool game, sometimes it is more difficult to control the tiny movement of the mouse pointer with the mouse, so I would like to write a program that can use the up, down, left, right and right keys of the keyboard to control the movement of the mouse by moving one pixel at a time.

This script depends on pywin32, pyHook and pymouse libraries, please install them yourself. The pythoncom in the code is part of the pywin32 library. Once you run the script, you can control the mouse movement with the up, down, left and right keys of your keyboard.

# -*- coding:utf-8 -*-
# Left 37 Up 38 Right 39 Down 40
 
import pythoncom
import pyHook
from pymouse import PyMouse
 
def onKeyboardEvent(event):
 # Get the id of the key pressed
 keyID =  
 # Get the coordinates of the current mouse
 mouse = PyMouse()
 x, y = ()
 x = int(x)
 y = int(y)
 
 # Set the x and y offsets
 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
 (x + deltaX, y + deltaY)
 return True
 
def main():
 # Start listening for keyboard events
 hm = ()
  = onKeyboardEvent
 ()
 ()
 
if __name__ == '__main__':
 main()

This is the whole content of this article.