Skip to content Skip to sidebar Skip to footer

Pygame Capture Keyboard Events When Window Not In Focus

I wrote a simple python script that gives control over the cursor to a joystick. My way to find out how this works is documented here. Now that works flawlessly but, as soon as I s

Solution 1:

I expect pygame sets up its own "sandbox" so that it's hard to detect input from outside its window. Your previous question indicates that you are also using the win32api module. We can use that to detect global key presses.

The correct way to detect key presses at the global scope is to set up a keyboard hook using SetWindowsHookEx. Unfortunately, win32api does not expose that method, so we'll have to use a less efficient method.

The GetKeyState method can be used to determine whether a key is down or up. You can continuously check the state of a key to see if the user has pressed or released it lately.

import win32api
import time

defkeyWasUnPressed():
    print"enabling joystick..."#enable joystick heredefkeyWasPressed():
    print"disabling joystick..."#disable joystick heredefisKeyPressed(key):
    #"if the high-order bit is 1, the key is down; otherwise, it is up."return (win32api.GetKeyState(key) & (1 << 7)) != 0


key = ord('A')

wasKeyPressedTheLastTimeWeChecked = FalsewhileTrue:
    keyIsPressed = isKeyPressed(key)
    if keyIsPressed andnot wasKeyPressedTheLastTimeWeChecked:
        keyWasPressed()
    ifnot keyIsPressed and wasKeyPressedTheLastTimeWeChecked:
        keyWasUnPressed()
    wasKeyPressedTheLastTimeWeChecked = keyIsPressed
    time.sleep(0.01)

Warning: as with any "while True sleep and then check" loop, this method may use more CPU cycles than the equivalent "set a callback and wait" method. You can extend the length of the sleep period to ameliorate this, but the key detection will take longer. For example, if you sleep for a full second, it may take up to one second between when you press a key and when the joystick is disabled.

Solution 2:

when your window gains or looses focus you get an ACTIVEEVENT. It's gain and state attributes tell you which state you've gained or lost. The easisest solution would probably be to catch this events in your main event loop and use them to keep track weather you have focus or not. Then you can just ignore joystick events if you don't have the focus.

Post a Comment for "Pygame Capture Keyboard Events When Window Not In Focus"