Mastering PyDirectInput: Streamlined Keyboard & Mouse Automation

Pypi provides us with a library to automate keyboard and mouse prompts. It’s pydirectinput. Earlier, users used to work with the PyAutoGUI library, but now we have a better alternative in the form of pydirectinput. Let us learn more about this library.

More about pydirectinput

This library works on Win32 API functions, specifically the SendInput() function, and is more compatible with software as compared to pydirectinput. It also provides you with the tools to play games, for software testing, etc.

The syntax

Let us now see how we can install this library. Use the pip command that is mentioned below either in the command prompt or terminal. Once you have installed it, you need to import it in order to use its functions.

pip install pydirectinput
import pydirectinput

Examples

There can be several types of input events. Some examples are given in the code block. You can use these to press the B key or release the A key. Also, there’s a functionality to move the cursor to given coordinates. In the third line of code, the curse will shift to 100,100 coordinates. The click() function allows a user to click the left mouse button. There are many other functions that work for the ease of a user.

pydirectinput.keyDown("b")
pydirectinput.keyUp("a")
pydirectinput.moveTo(100, 100)
pydirectinput.click()

pydirectinput-rgx 2.1.0

This is an extension or a fork of the pydirectinput library. It has a few improvements like-

  • Support for Unicode characters
  • Support for keyboard shortcuts
  • Support for multiple keyboards
  • More precise control over function behavior

It is more advanced and has less bugs. If you want basic features, you can keep using the pydirectinput library only.

Does pydirectinput work on Mac?

This library is Windows-based. Therefore, it does not work on Mac. For Mac users, there is an alternative: pynput and keyboard libraries. pynput library works on generating keyboard listeners. The following code depicts how you can use the keyboard library.

import keyboard

# Wait for a key to be pressed
key = keyboard.read_key()

# Print the pressed key
print(f"Pressed: {key}")

How to read keyboard input with pydirectinput?

The pydirectinput library doesn’t have a well-defined function that works solely for this purpose. However, you can use three functions for the same:

  • keyDown()
  • keyUp()
  • waitKey()

These functions help you with key presses. You should notice the return value while using the keyDown() function. If you obtain the answer as TRUE, it means that you pressed that particular key else you didn’t. Use the keyUp() function to release the key press. Now, you can check the given code to see how pydirectinput works with keyboard input using the keyUp() and keyDown() functions.

import pydirectinput

# Wait for a key to be pressed
key = pydirectinput.keyDown()

# Print the pressed key
print(f"Pressed: {key}")

# Wait for the key to be released
pydirectinput.keyUp(key)

The next function that you may consider for this purpose is the waitKey() function. In this case, if you press the key, you will get the key code.

import pydirectinput

# Wait for a key to be pressed
key_code = pydirectinput.waitKey()

# Print the key code of the pressed key
print(f"Key code: {key_code}")

There is another way through which you can access the keyboard inputs through the waitKey() function. You may check for several keys by putting this function in a loop. Consider the example given below. It basically uses a loop and checks the key code to note if a key has been pressed or not.

import pydirectinput

# Create a list to store the pressed keys
pressed_keys = []

# Start a loop to listen for key presses
while True:

    # Wait for a key to be pressed
    key_code = pydirectinput.waitKey()

    # If the key code is not equal to `-1`, then the key is pressed
    if key_code != -1:

        # Add the pressed key to the list
        pressed_keys.append(key_code)

    # If the key code is equal to `-1`, then the loop is broken
    else:
        break

# Print the pressed keys
print(f"Pressed keys: {pressed_keys}")

Creating scripts with pydirectinput

You can create Python scripts using the pydirectinput library too. In order to create the script, you should follow these steps:

  • Importing pydirectinput library
  • Defining script code
  • Using pydirectinput’s functions to get keyboard input
  • Save the script as .py file
  • Run this .py file.

The following code demonstrates how you can create a Python script. The loop works for 10 iterations. It presses A ten times.

import pydirectinput

# Define a function to press the "A" key
def press_a():
    pydirectinput.keyDown("a")
    pydirectinput.keyUp("a")

# Press the "A" key 10 times
for i in range(10):
    press_a()

# Save the script as a Python file
with open("example.py", "w") as f:
    f.write(code)

# Run the script
import example
example.press_a()

Similarly, you can use other functions like keyDown(), keyUp(), moveTo(), click(), scroll() and type().

PyDirectInput to simulate keyboard shortcuts

You can represent keyboard shortcuts with the aid of this library also. For this purpose, you can use the keyDown() function. The following example illustrates how you can create the Ctrl+C keyboard shortcut and stimulate it.

pydirectinput.keyDown("ctrl")
pydirectinput.keyDown("c")
pydirectinput.keyUp("ctrl")
pydirectinput.keyUp("c")

pydirectinput not working in game

Certain games consist of anti-automation measures. These can block pydirectinput. Also, your game may be running as an administrator. You should use the pydirectinput.keyDown() and pydirectinput.keyUp() functions in place of pydirectinput.press() function. If the issue persists, you can switch to the pyautogui library. Also, you may use AutoHotkey to record your script and then run it with this library. Updating the library will also help.

pydirectinput right click

There is no predefined function for right-clicking in the pydirectinput library. You can try this with the click(button='right') function. However, this may not work for all game applications.

import pydirectinput

# Move the mouse to the desired location
pydirectinput.moveTo(x, y)

# Perform the right-click
pydirectinput.click(button='right')

The other method involves combining the keyDown and keyUp functions provided by pydirectinput. Through this code, you can press and release the right mouse button.

import pydirectinput

# Move the mouse to the desired location
pydirectinput.moveTo(x, y)

# Press and release the right mouse button
pydirectinput.keyDown('right')
pydirectinput.keyUp('right')

pydirectinput hold

This library doesn’t offer an exact hold function in order to hold a key. Still, you can achieve this using keyDown a function with an infinite loop. This will press and release the key after putting it to sleep() for a specified time.

import pydirectinput
import time

# Define the key to hold
key_to_hold = 'w'

# Move the mouse to the desired location (optional)
# pydirectinput.moveTo(x, y)

# Hold the key indefinitely
while True:
    pydirectinput.keyDown(key_to_hold)
    time.sleep(0.1)  # Adjust delay based on desired hold duration
    pydirectinput.keyUp(key_to_hold)

pydirectinput moveto

The moveTo function of the pydirectinput library helps to move the mouse cursor to a location on the screen. It has two mandatory and two optional parameters. These are:

  • x_coordinate: It refers to the horizontal coordinate (X-axis) of your desired location.
  • y_coordinate: It is the vertical coordinate (Y-axis) of your desired location.
  • duration (Optional): It refers to the time taken to move the cursor to the target location. The default value is 0.
  • _pause (Optional): It is used to suggest whether you need to pause after movement. Its default value is True.

The following example illustrates this.

import pydirectinput

# Define the target coordinates
x_coordinate = 100
y_coordinate = 200

# Move the mouse cursor to the target coordinates
pydirectinput.moveTo(x_coordinate, y_coordinate)

Pydirectinput vs. PyAutoGUI vs. Pynput vs AutoHotkey

Now, let us see how pydirectinput is different from PyAutoGUI, Pynput, and AutoHotkey. The table given below sets these libraries apart from each other on various factors like Platform, Speed, Efficiency, Features, Documentation, and Ease of use.

FeaturePyDirectInputPyAutoGUIPynputAutoHotkey
PlatformWindowsCross-platformCross-platformWindows
SpeedFastMediumMediumMedium
EfficiencyEfficientMediumMediumMedium
FeaturesKeyboard and mouse inputKeyboard and mouse input, image recognition, screen captureKeyboard and mouse input, joystick, and controller inputKeyboard, mouse, joystick, and controller input, scripting language
DocumentationGoodGoodGoodGood
Ease of useEasyEasyMediumDifficult

FAQs

Is PyDirectInput only available for Windows?

Yes. It works on Windows only.

Can I use PyDirectInput to play games?

Yes, you can. However, some games may not support this library.

Conclusion

By now, you must know the basics of the pydirectinput library. This article also covers the syntax of pydirectinput along with its usage on Windows. It draws differences among some Python libraries, which are similar to pydirectinput.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments