-
Notifications
You must be signed in to change notification settings - Fork 244
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to listen Key combination? #20
Comments
Thank you! The listener does not maintain a list of the currently pressed keys---this would be a new, quite reasonable, feature. You can however emulate that using the following snippet: from pynput import keyboard
# The key combination to check
COMBINATION = {keyboard.Key.cmd, keyboard.Key.ctrl}
# The currently active modifiers
current = set()
def on_press(key):
if key in COMBINATION:
current.add(key)
if all(k in current for k in COMBINATION):
print('All modifiers active!')
if key == keyboard.Key.esc:
listener.stop()
def on_release(key):
try:
current.remove(key)
except KeyError:
pass
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join() This works as expected, with the following caveat: If one of the modifier keys is pressed before the listener is started, it has to be released and pressed again for the program to detect it. I will update the road map in the wiki. |
Thank you for your replay, I learn a lot 🙏 |
Hi, Thanks for the lib How can I combine your above example with a regular character to create a hotkey? IE shift+ctrl+alt+x causes some code to execute. Thanks |
keyboard.KeyCode.from_char('x') or its alike works fine for alphanumeric keys. |
@moses-palmer How are you able to modify the https://stackoverflow.com/questions/4522786/modifying-a-global-variable-inside-a-function |
You cannot assign to a global variable unless declaring it using global,
since that would instead introduce it into the local scope, but you may
freely mutate global variables.
…On Sun, 1 Apr 2018, 15:37 Dev Aggarwal, ***@***.***> wrote:
@moses-palmer <https://github.com/moses-palmer> How are you able to
modify the current varialbe from a function. AFAIK, it's not possible to
modify global variable from inside a function in python without explicity
declaring global in your function definition.
https://stackoverflow.com/questions/4522786/modifying-a-global-variable-inside-a-function
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#20 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAjOY8x86qEFNQVWfYlYULFwBroy8Eixks5tkNgigaJpZM4MvV4j>
.
|
That explains it, thanks! Here is a modified version that also prints a message when you release that key combination!
|
Sorry to bump this up again, is just a question because maybe I'm misunderstanding something. In [1]: from pynput import keyboard
In [2]: keyboard.Key.ctrl
Out[2]: <Key.ctrl: <17>>
In [3]: keyboard.Key.ctrl_l
Out[3]: <Key.ctrl_l: <162>>
Thank you! |
You are correct in assuming that In the case of comparisons, however, things do get a bit tricky, especially considering I guess a possible solution is to add a set of alternate key codes for each |
Thank you @moses-palmer, I thought so, this is the code I used if anyone needs this. As a small bonus the following code listens only to double pressing of ctrl + c in less than a second: from pynput import keyboard
import datetime
# The key combinations to check
COMBINATIONS = [
{keyboard.Key.ctrl_l, keyboard.KeyCode(char='c')},
{keyboard.Key.ctrl_r, keyboard.KeyCode(char='c')}
]
# The currently active modifiers
current = set()
tnow = datetime.datetime.now()
tcounter = 0
def on_press(key):
if any([key in comb for comb in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in comb) for comb in COMBINATIONS):
global tnow
global tcounter
tcounter += 1
if datetime.datetime.now() - tnow < datetime.timedelta(seconds=1):
if tcounter > 1:
tcounter = 0
main_function()
else:
tnow = datetime.datetime.now()
if key == keyboard.Key.esc:
listener.stop()
def on_release(key):
try:
current.remove(key)
except KeyError:
pass
def main_function():
print('Main function fired!')
# rest of your code here...
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join() If you have comments on above code to improve it or any suggestions (in particular the rather sloppy Thank you. |
Hi @GlassGruber, I tried your code, but for some reason (I am on Windows) my "c" or "v" is like this only when pressed alone. When I have ctrl pressed, I get '\x16' '\x13' and don't match the combination.... @moses-palmer do you have any hint? |
On a mac (changing the ctrl to cmd) I get the 'v' as '√' |
Does anyone have any idea how to fix this? @521xueweihan? @devxpy? @moses-palmer? @GlassGruber? |
What version do you use? Commit 63aab1a, included in pynput 1.4, introduces a fix for keyboard layout handling, which is especially notable when running the application in a command window. I have tested the code in @GlassGruber's comment using the master branch, which correctly identified Ctrl + C, and with that commit reverted, which caused your issue with only a non-ASCII key being generated. Note that this on Windows; the Mac issue is different, and unresolved. Running the test script and printing all characters reveal that all alphanumeric keys are altered. Ctrl + C does work however; perhaps the simple and necessary solution is to add a special case for macOS? Using Cmd already mandates this. |
@moses-palmer I've tried the pynput 1.4 and the master. I've used this: (I also changed 'c' for 'v' and ctrl for cmd on mac) def on_press(key):
print('KEY', key)
try: print('CHAR', key.char) # letters, numbers et
except: print('NAME', keyboard.KeyCode().from_char(key.name)) On Mac High Sierra - sequence: cmd / v / cmd+v Windows 10 and Ubuntu 18 - sequence: ctrl / v / ctrl+v |
Hi GlassGruber Thanks I edited your code so I can use in my script basiclly I need to break a while loop. with ctrl - q Here is it
|
Sorry, I don't get it how to use join(key) correctly. |
Any progress on implement the key combination feature for this project ? |
So I wrote some code & its causing me a headache. I want to have two different combinations. The code I wrote the first combination of keys Ctrl+G or g work but Ctrl + H or h did not but crashes the program. I have re-written my code so many times trying to figure it out that it does not makes sense. Any help? Please help me! I'm really new to python! Indentation is not working, but if you look at the .txt it is there. from pynput import keyboard COMBINATIONS = [ COMBINATIONS2 = [ def execute1(): #Function call for character Ctrl G or Ctrl g def execute2(): #Function call for character Ctrl H or Ctrl h def on_press(key): def on_release(key): with keyboard.Listener(on_press=on_press, on_release=on_release) as listener: |
Using the given snippet, dead keys pollute the list and make further comparisons break. For example, when typing in Shift+t, a 'Shift' will be added, then a 'T'. If you then release the Shift, you are left with a 'T', and releasing 't' does not remove it, and the set now will keep containing 'T'. Is there a way to disable registering dead keys? As a current solution, I remove the last element in the list when a key is released, ignoring which key it actually is. |
See |
@platelminto, if you run into issues with dead keys, you may want to take a look at #118. The branch fixup-win32-keyboard-listener has a proposed solution. |
How do we capture the windows super key events like (windows+r or windows+m etc) |
Can you give an example? |
Sorry about my last sentence, It's happened due to misunderstanding so I deleted it |
@platelminto Had the same problem. I solved it by tracking the shift key down / shift key up movements. |
I was looking for a way to detect multiple keypresses at once, and this seemed to be the answer. The only problem is that, for whatever reason, only two keys can be returned at the same time (with occasional exception). How do I detect 3+ keyboard inputs at once? |
It seems that pyinput can't handle three or more events at the same time, and where it always replaces the second key with the third. From the looks of it it does this without calling the on_release event. |
Great library!
When I use the
pynput
I want to listen the key combination, Such as: ctrl+cmdI can't find the way to do that,So I ask you for help.👻
The text was updated successfully, but these errors were encountered: