2

I was writing this type-recording program when I encountered a problem - Alt key doesn't have an Ascii number so I can't hook it in the regular way. This is my source code without the Alt hooking try, the question is - how do I hook Alt? I know that there is Class variable named "Alt" and built-in function named "IsAlt" but I didn't get how to use them.

import pythoncom,pyHook

log = ""
logpath = "log.txt"

openfile = open(logpath,"w")
openfile.write("")

def OnKeyboardEvent(event):
    try:
        global log
        if event.Ascii == 8:
            log = "[BS]"
        elif event.Ascii == 9:
            log = "[TAB]"
        elif event.Ascii == 13:
            log = "[NL]"
        elif event.Ascii == 27:
            log = "[ESC]"
        elif event.Ascii == 15:
            openfile.close()
            exit()
        else:
            log = chr(event.Ascii)
        openfile.write(log)
    except:
        pass

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
L Y E S - C H I O U K H
  • 4,765
  • 8
  • 40
  • 57
Doron
  • 161
  • 2
  • 5
  • 13
  • I believe on each KeyboardEvent you have to check whether `event.Alt` is also set to detect whether the Alt modifier key was held down at the same time. I would suggest running the [example](http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=PyHook_Tutorial#Keyboard_Hooks) code and observing what event data is generated for different key combinations. – martineau Nov 21 '12 at 13:58
  • thanks, it was realy helpful! – Doron Nov 21 '12 at 14:55
  • You're welcome. Happy hooking! ;-) – martineau Nov 21 '12 at 14:57

1 Answers1

0

Instead of using event.Ascii when mapping keys, use event.KeyID.

Note that keys like AltGr have 2 mapping IDs: one for pressed key and another for released key.

Matheus Santz
  • 538
  • 6
  • 7