1

Can we make some global keybindings with python?

I mean when I'm in another application or game if I press X the code do something. I searched for that but only found for Ubuntu or Linux... But I want something for Windows and Python3.x.


Solution: https://pynput.readthedocs.io/en/latest/keyboard.html#global-hotkeys
PokerFaCe
  • 329
  • 2
  • 11
  • You can convert your script into an executable exe and use winhotkey to map it to a shortcut key combination. – Nalin Angrish Aug 24 '20 at 10:38
  • Thanks @NALIN_yo. this is a good idea. I don't need to convert my script to an exe file. I can create `.bat` files who run my scripts. but I want to use my own app not winhotkey or etc for Keybinding. – PokerFaCe Aug 24 '20 at 22:59
  • You can use pynput for detecting hotkeys. This documentation can help: https://pynput.readthedocs.io/en/latest/keyboard.html#global-hotkeys – Nalin Angrish Aug 25 '20 at 09:12
  • Have you tried the tutorial above @PokerFaCe ? – Nalin Angrish Aug 31 '20 at 13:28
  • Yes. that solved my problem. I added another answer and I said it. but deleted. thanks. @NALIN_yo – PokerFaCe Sep 09 '20 at 17:33

1 Answers1

3

This is what I found, which works well.
using the module pynput. It will listen to key press globally. I found the answer here stackoverflow.com/questions/11918999/key-listeners-in-python

from pynput import keyboard

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()
Krunal Sonparate
  • 1,122
  • 10
  • 29
jon stokes
  • 46
  • 3