2

I am trying to route keyboard presses detected by a simple keylogger to another thread. My program sets up key logging in a thread like this:

import threading
import Queue
import pythoncom
import pyHook

stopevent = threading.Event() #how to stop each thread later
q1 = Queue.Queue() #a threading queue for inter proc comms

def OnKeyboardEvent(event):
    return event

def thread1(q1,stopevent):
    while (not stopevent.is_set()):
        print q1.get() #print what key events are registered/pumped

def thread2(q1,stopevent):
    hm = pyHook.HookManager()
    hm.KeyDown = OnKeyboardEvent
    hm.HookKeyboard()
    while (not stopevent.is_set()):
        pythoncom.PumpWaitingMessages()
        #q1.put(something????)
    hm.UnhookKeyboard()

t1 = threading.Thread(target=thread1,args=(q1,stopevent))
t2 = threading.Thread(target=thread2,args=(q1,stopevent))

t1.start()
t2.start()

I am trying to route the "event" captured by the hook into q1, which will then make it available to thread1 for whatever. You'll notice my code does not make an important call of q1.put(). Truth be told I programmed the "OnKeyboardEvent" function to return the event but I have no idea where it is returned to, or how to get it. This is what I need help with. I looked in the HookManager() class definition and didn't see anything I thought I could use.

And for any conscientious programmers out there, this is for science, not hacking. I'm trying to control a treadmill's speed based on keyboard inputs.

willpower2727
  • 769
  • 2
  • 8
  • 23

1 Answers1

1

Well this is dirty but I found a way to do this by making a simple change to the HookManager class definition in HookManager.py. It's open source afterall...

I made the following changes to HookManager class:

def __init__(self):
    #add the following line
    self.keypressed = '' #make a new class property

I also added the following method to the HookManager class:

def OnKeyboardEvent(self,event):
    self.keypressed = event.key
    return True

Those are the modifications to HookManager, now when I make my threads I can do this:

import threading
import Queue
import pythoncom
import pyHook

stopevent = threading.Event() #how to stop each thread later
q1 = Queue.Queue() #a threading queue for inter proc comms

def thread1(q1,stopevent):
    while (not stopevent.is_set()):
        print q1.get() #print what key events are registered/pumped

def thread2(q1,stopevent):
    hm = pyHook.HookManager()
    hm.KeyDown = hm.OnKeyboardEvent
    hm.HookKeyboard()
    while (not stopevent.is_set()):
        pythoncom.PumpWaitingMessages()
        q1.put(hm.keypressed)
    hm.UnhookKeyboard()

t1 = threading.Thread(target=thread1,args=(q1,stopevent))
t2 = threading.Thread(target=thread2,args=(q1,stopevent))

t1.start()
t2.start()

Now I can get whatever key was pressed from the hookmanager itself and pass that along to other threads. Like I said, not really elegant but it works.

willpower2727
  • 769
  • 2
  • 8
  • 23