-1

How can I catch a key press in my program, but it won't be caught by other applications?

I know this is possibly a dupe of Is it possible to intercept key presses with python? but I did not find any descriptive answers in there.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    I don't understand what you're asking. Can you read in keys in your python program? Yes. That's what the `input` function is for. Will other applications see that keypress? Literally no way to answer that because as long as a program has the right OS permissions, it can look at whatever it wants. It's how debuggers work. So _can_ it be seen by other programs? Sure, with a lot of work. _Will_ it be seen? Not a question that has an answer. Is it _likely_ to be seen? No, but that information isn't useful. – Mike 'Pomax' Kamermans Feb 27 '23 at 00:59
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 27 '23 at 02:54

1 Answers1

0

Interesting idea. We could create a quick "key-logger" script in Python using the pynput library. The implementation is pretty simple and only entails the following lines of code (taken from the docs).

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))


listener = keyboard.Listener(on_press=on_press)
listener.start()

This gif shows how this would run.

However if you were looking for key presses to be entirely redirected to a Python program, then the solution will probably be more involved and probably entail some fiddling with the keyboard buffer.

F-said
  • 1