2

I was working on a keylogger to learn a bit about pyHook, but it seems like event.Ascii gives me the wrong ASCII values. For example I get 0 for any symbol or number, 1 for A (should be 65), etc.

import pyHook, pythoncom

def OnKeyboardEvent(event):
    key = chr(event.Ascii)
    print(key)
    return 0
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

I found a kind of a fix for it, which is using event.KeyID instead of event.Ascii. However, because of that I only get letters and numbers - symbols are totally wrong.

Is this a Python problem, or some kind of keyboard problem?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Same question here http://stackoverflow.com/questions/37865445/pyhook-keydown-wrong-event-ascii-values , but no answers. – RemcoGerlich Jan 14 '17 at 16:31
  • @RemcoGerlich: that poster's sample output disappeared, so it's no longer useful ... ("And that's why, kids, you should never include textual output as an image.") – Jongware Jan 14 '17 at 16:35
  • 1
    @RadLexus It was a Pastebin link, not an image. But yeah, I left a note for the OP. – Tagc Jan 14 '17 at 16:39
  • had a quick look and when i tried with print('Ascii:', event.Ascii, chr(event.Ascii)) ,I am getting correct output for numbers (tested in python 3.4) – ClumsyPuffin Jan 14 '17 at 18:04
  • Not working in python 3.5, no idea what's wrong. – Shadowphyre Jan 14 '17 at 18:20

1 Answers1

0

Parsing the KeyIDs manually seems to be the only option, here's how I did it:

import logging
import pyHook, pythoncom

def on_keyboard_event(event):
    mappings = {None: "<backspace>", 8: "<del>", 13: "\n", 27: "<esc>", 32: " ", 46: "<del>", 91: "<win>",
                160: "<shft>", 162: "<ctr>", 164: "<alt>", 165: "<ralt>", 9: "<tab>",
                48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9",
                37: "←", 38: "↑", 39: "→", 40: "↓",
                192: "ö", 222: "ä", 186: "ü", 187: "+", 191: "#",
                188: ",", 190: ".", 189: "-", 219: "ß", 221: "´",
                }

    try:
        id = event.KeyID
        char = mappings.get(id, chr(id).lower())
        if not id in mappings and char not in alpha:
            char = "<%s,%s>" % (char, str(event.KeyID))
        print(char, end="")
    except Exception as e:
        logging.exception(e)

    return True


hm = pyHook.HookManager()
hm.KeyDown = on_keyboard_event
hm.HookKeyboard()
pythoncom.PumpMessages()

This is for a German keyboard layout, so you may want to edit the mappings. Some keys are also still missing, so feel free to extend or improve this post.

dominik andreas
  • 155
  • 1
  • 7