PyAutoGUI seems to ignore numpad key presses

194 views Asked by At

I'm using Windows, Python, and PyAutoGUI to try to automate some activities in Minecraft as a fun project.

I have been successful with using PyAutoGUI to switch to Minecraft once I start the script in Visual Studio Code, click on the "Back to Game" button, and then move the avatar forward by holding the "w" key.

I am using a 3rd party program called "NeatMouse" to use my numpad keys in place of using a mouse. The numpad 8 button is equivalent to moving the mouse up, which in Minecraft causes your avatar to look up. When I press this button myself in Minecraft, it works as expected, so it must be the case that NeatMouse is not the problem.

When I try to have PyAutoGUI replicate this same key press, it seems like nothing is happening.

I have tried different combinations of

  • pag.press()
  • pag.hold()
  • pag.keyDown() & pag.keyUp()

These functions do work for the WASD keys, so I know that Minecraft is able to receive keyboard input from PyAutoGUI, so that generally must not be the problem.

Here is a sample code block of what I have tried.

import pyautogui as pag
def align_vertical_facing_axis(target):
    facing = get_facing_axes()[1]
    
    # Looking down
    if facing > target:
        print('torture')
        pag.keyDown('num8')
        sleep(1)
        pag.keyUp('num8')

get_facing_axes() is a function I wrote to retrieve the axes the avatar is facing as a tuple from the Minecraft debug screen. A positive value in the [1] index means the character is looking at a downward angle. When I run this script, it does print "torture" to my console so I know for sure it is entering that "if" block.

That was the long version of the explanation, the short version is: PyAutoGUI won't press the numpad keys, what do??

1

There are 1 answers

0
Lashen On

After some research, pyautogui.platformModule contains the mappings for numpad.

Here are the windows key mappings: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

import pyautogui as pag

#This is where you update key mappings, num8 is now referring to the virtual key code VK_NUMPAD8 or 0x68 

pag.platformModule.keyboardMapping.update({'num8':0x68}) 

#To call it, you use the mapping name you gave to the virtual key code
pag.press('num8')

Use the list I gave you for other key mapping values such as 0x68 for num8 and so on.