0

Whenever I press the ESC key (anywhere on my desktop), I would like to print a message.

This is what I have so far:

from msvcrt import getch
while True:
    key = ord(getch())
    if key == 27:
        print('Key pressed.')

When I run this code and hit ESC, I get nothing - not even an error. Why?

print(key) keeps giving me 255 repeatedly, even if I press nothing.

Reza Saadati
  • 5,018
  • 4
  • 27
  • 64

1 Answers1

2

Your code works just fine if you open the script through the console (double click on the file, not with IDLE).

You want a low-level keyboard hook. This simply listens to the keypresses made to the console, not anywhere else.

Mothrakk
  • 70
  • 1
  • 9
  • 1
    Yeah this [stack overflow](https://stackoverflow.com/questions/16076853/using-msvcrt-getch-in-eclipse-pydev) discussion talks about how it doesn't work unless you use the console or another method. – Professor_Joykill Jul 06 '17 at 18:40