J
J
JRazor2014-03-29 16:09:04
Python
JRazor, 2014-03-29 16:09:04

Python: how to catch keyboard shortcuts?

Hello. I'm using win32api to emulate keystrokes. Everything is clear and simple here. But how can you catch keystrokes?
For example, I assigned the keyboard shortcut Ctrl + Shift + Home, and if they are pressed, the script was launched.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
TomasHuk, 2014-06-12
@JRazor

Also very interested in this question. If there is a solution, drop the python code here in the comments.
PS (two days later) I solved the issue.

import win32api
import pythoncom
import pyHook

def OnKeyboardEvent(event):
    # проверяем статусы клавиш-модификаторов
    # возвращаемые значения:
    # 0 или 1 - клавиша отжата
    # (-127) или (-128) - клавиша нажата
    ALT     = win32api.GetKeyState(0x12)    #
    CTRL    = win32api.GetKeyState(0x11)
    SHIFT   = win32api.GetKeyState(0x10)
    LWIN    = win32api.GetKeyState(0x5B)
    HOME    = win32api.GetKeyState(0x24)
    if event.Key=='Home' and event.MessageName == 'key down':
        if CTRL<0 and SHIFT<0 and ALT<0:
            print('Нажата комбинация клавиш CTRL+SHIFT+ALT+HOME')
        elif CTRL<0 and SHIFT<0:
            print('Нажата комбинация клавиш CTRL+SHIFT+HOME')
        elif ALT<0 and SHIFT<0:
            print('Нажата комбинация клавиш SHIFT+ALT+HOME')
        elif CTRL<0 and ALT<0:
            print('Нажата комбинация клавиш CTRL+ALT+HOME')
        elif CTRL<0:
            print('Нажата комбинация клавиш CTRL+HOME')
        elif SHIFT<0:
            print('Нажата комбинация клавиш SHIFT+HOME')
        else:
            print('Нажата клавиша HOME')
    return True

hm = pyHook.HookManager()       # создание экземпляра класса HookManager
hm.KeyAll = OnKeyboardEvent     # отслеживаем нажатия клавиш
hm.HookKeyboard()               # вешаем хук
pythoncom.PumpMessages()        # ловим сообщения

Tested on Win7, python 3.3.
Helped this post , a table of virtual key codes and documentation on win32api and pyHook .

J
jcmvbkbc, 2014-03-29
@jcmvbkbc

msdn.microsoft.com/en-us/library/windows/desktop/m...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question