Skip to content Skip to sidebar Skip to footer

Create Keyboard Shortcut?

I am searching for a way to create a cross-platform keyboard shortcut in Python. Such that when I press something like Ctrl+C or Ctrl+Alt+F, the program will run a certain function

Solution 1:

I don't know is it possible to send combinations of Ctrl and/or alt. I tried couple of times but I think it doesn't work. (If someone has any other information please correct me). What you can do is something like this:

from msvcrt import getch

whileTrue:
    key = ord(getch())
    if key == 27: #ESC
        PrintSomething()

defPrintSomething():
    print('Printing something')

this will run a scrpit every time you press ESC although it will only work when you run it in command prompt.

Solution 2:

You can create a listener for keypress event by pynput library. this is a simple code that run a function when press CTRL+ALT+H keys:

from pynput import keyboard

defon_activate():
    print('Global hotkey activated!')

deffor_canonical(f):
    returnlambda k: f(l.canonical(k))

hotkey = keyboard.HotKey(
    keyboard.HotKey.parse('<ctrl>+<alt>+h'),
    on_activate)
with keyboard.Listener(
        on_press=for_canonical(hotkey.press),
        on_release=for_canonical(hotkey.release)) as l:
    l.join()

Post a Comment for "Create Keyboard Shortcut?"