【问题标题】:Returning pyhook keypress event to thread queue将 pyhook 按键事件返回到线程队列
【发布时间】:2016-09-06 19:18:37
【问题描述】:

我正在尝试将简单键盘记录器检测到的键盘按下路由到另一个线程。我的程序在这样的线程中设置密钥日志记录:

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()

我正在尝试将钩子捕获的“事件”路由到 q1,然后它将使其对 thread1 可用。您会注意到我的代码没有对 q1.put() 进行重要调用。说实话,我编写了“OnKeyboardEvent”函数来返回事件,但我不知道它返回到哪里,或者如何获取它。这是我需要帮助的。我查看了 HookManager() 类定义,没有看到任何我认为可以使用的东西。

对于任何尽职尽责的程序员来说,这是为了科学,而不是黑客。我正在尝试根据键盘输入来控制跑步机的速度。

【问题讨论】:

    标签: python-2.7 queue python-multithreading keylogger pyhook


    【解决方案1】:

    这很脏,但我找到了一种方法,方法是对 HookManager.py 中的 HookManager 类定义进行简单的更改。毕竟是开源的...

    我对 HookManager 类进行了以下更改:

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

    我还在 HookManager 类中添加了以下方法:

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

    这些是对 HookManager 的修改,现在当我创建线程时,我可以这样做:

    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()
    

    现在我可以从 hookmanager 本身获取按下的任何键并将其传递给其他线程。就像我说的那样,不是很优雅,但它确实有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 2016-06-22
      • 1970-01-01
      相关资源
      最近更新 更多