jacobsskowronek
jacobsskowronek

Reputation: 11

Python pyHook returning invalid characters (boxes instead of characters)

I am trying to make a simple program that logs all keystrokes, and I am having a hard time figuring out how to get it to work. i can't seem to find a solution to this problem anywhere.

I am using pyHook to get my keystrokes and I have created a function called OnKeyboardEvent(event) that should be taking the event ascii and converting it to a char in order to put it into a file, but the file only contains boxes, or what I assume are some kind of invalid characters. After a fair bit of debugging, I figured out that printing out the ascii character itself rather than the char converted still outputs the weird boxes. Any insight as to what is going on is very much appreciated.

These are the parts of the important bits of the OnKeyboardEvent function:

def OnKeyboardEvent(event):

    if event.Ascii == 5:
        sys.exit(0)
    if event.Ascii != 0 or 8:
        f = open(file, 'r+')
        buffer = f.read()
        f.close()

        f = open(file, 'w')
        keylogs = chr(event.Ascii)
        print (keylogs)

Here is the part that hooks the keyboard

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()

pythoncom.PumpMessages()

I am running Windows 10 and opening the file with notepad if that has anything to do with the problem

Upvotes: 1

Views: 874

Answers (1)

Areg Hovhannisyan
Areg Hovhannisyan

Reputation: 110

Well, try event.KeyID instead of event.Ascii. Not sure if this is the best solution, but works for me.

Upvotes: 1

Related Questions