3

I am creating a small app for myself to be able to show my keyboard inputs and show them in a Joystick layout, like this:

Current view of my App

This itself, works perfectly fine while the Pygame windows is focused, my problem is, i can't have this focused all the time, in fact it will never have focus because either way i will be using OBS to stream or i will be using my emulator, and pygame doesn't detect inputs that are out of the window. Is there any way to make python or pygame read all the input made to the computer??? I am hitting a wall here. Thanks in advance!!

NyxTheShield
  • 69
  • 1
  • 9
  • Pygame can't do that for you with its event handling, since it only listens to window events. What you're looking for a low-level hooks, take a look here [Applying low-level keyboard hooks with Python and SetWindowsHookExA](https://stackoverflow.com/questions/9817531/applying-low-level-keyboard-hooks-with-python-and-setwindowshookexa) for an example. – sloth Jul 22 '15 at 08:04

3 Answers3

5

There's an SDL environment variable for this! Simply setting it will enable background input.

import os
os.environ["SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"] = "1"

Add that to the top of the sample in the joystick docs and try it out.

Tested with pygame 2.1.2, sdl 2.0.18, Windows 10 (21H2), Xbox One like controller

ref:

Old Badman Grey
  • 668
  • 10
  • 19
1

Use pygame.event.set_grab(True)

When your program runs in a windowed environment, it will share the mouse and keyboard devices with other applications that have focus. If your program sets the event grab to True, it will lock all input into your program. It is best to not always grab the input, since it prevents the user from doing other things on their system.

You will need another way to exit though, since you will not be able to move the mouse out of the display window.

Luke B
  • 2,075
  • 2
  • 18
  • 26
1

As per two comments directly above, IN order to keep focus on the pygame window (effectively keep the cursor within the bounds of the pygame window until a I was able to make this work with the following code:

pygame.event.set_grab(True) # Keeps the cursor within the pygame window

Combine this code with a way to quit the program with a key press such as the ESCAPE key (since it will be impossible to close the window by moving your cursor to the frame of the window to close it that way by pygame.QUIT):

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
            run = False
thescoop
  • 504
  • 5
  • 20