2

I have this program in pycharm python3.8 that i need to detect if ctrl+c is pressed anywhere while browsing windows while the program is running, but for some reason the program does not detect if the pressed key is the "ctrl" my code looks like this:

from pynput import keyboard

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.add(key)
        if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
            print("Ctrl+C pressed")

def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.remove(key)

COMBINATIONS = [
    {keyboard.Key.ctrl, keyboard.KeyCode(char='c')}
]

current = set()

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

It never gets to print the message. I am running the program on Windows 10 Pycharm internal command line

Thanks!

Ptmlol
  • 37
  • 2
  • 6

2 Answers2

3

Try this code :

try:
    while True: ### YOUR CODDE
        pass    ### 
except KeyboardInterrupt:
    print('You pressed ctrl+c')

Without any library and fastest method

Yash Makan
  • 706
  • 1
  • 5
  • 17
  • Yes, but run the OP's program... It continues monitoring keyboard input no matter what window you're in. Also you're running inside the pycharm console, pycharm traps `^C` to mean "copy" and the keypress never makes it to your program. – tangentstorm Dec 06 '20 at 12:01
  • Yes, i need to run the program permanently @tangentstorm you mean, if i would run the command outside the pycharm console, it would be better? – Ptmlol Dec 06 '20 at 12:23
1

To see what's happening, add a line to the top of on_press that shows each keypress:

def on_press(key):
   print(key,)
   # ...

When you press ^C, you'll notice you get \x03... This is one of the ASCII control characters. Most of them aren't really used that much these days, but this was originally the whole point of the control key. :D

It looks like in pynput, you can catch ^C by testing against chr(ord("C")-64)... And the same for all the other control characters.

(BTW, Thanks for telling us about pynput. So much easier than what I used in the past!)

Edric
  • 24,639
  • 13
  • 81
  • 91
tangentstorm
  • 7,183
  • 2
  • 29
  • 38
  • Thanks, but i see that with my program like this, if i print something to the top of ``` on_release``` i get the message that the ```ctrl``` has been released before pressing ```c```. (BTW You're welcome! Pynput rocks! – Ptmlol Dec 06 '20 at 12:26
  • 1
    Can you give me an example on my code on how to implement ```chr(ord("C")-64)```, i am pretty new to python, sorry! Thanks in advance! – Ptmlol Dec 06 '20 at 12:29
  • 1
    @Ptmlol that is literally the python code to figure out the character for ^C. `chr()` and `ord` are python builtins. So maybe `def ctrl(letter): return chr(ord(letter.upper())-64)` and then `if key == ctrl("C"):` in your code. – tangentstorm Dec 06 '20 at 13:20