如何停止执行pythoncom.PumpMessages()

时间:2018-07-30 10:25:18

标签: python python-3.x pythoncom

我正在使用带有逃逸按钮的键盘记录器将其停止:

if event.Ascii == escape_button_ascii:
            sys.exit()

发布在底部的其余代码

我正在使用from key_logger import start_key_loggerstart_key_logger()从另一个文件调用此文件,并且我希望该脚本在检测到escape_button_ascii之后继续执行。除了sys.exit()之外,还有什么我可以杀死键盘记录器本身的东西吗?


我尝试将hook_manager保存到全局文件中,并在检测到escape_button_ascii时执行unhookKeyboard() + unhook_flag = True。该标志已在 while True: try: pythoncom.PumpMessages() except: pass if unhook_flag: return

中签入

但这只会停止键记录(unhookKeyboard()),但不会返回键,这意味着我仍然停留在此功能中,无法继续。

总而言之,我设法停止了实际的按键记录,但是未能停止pythoncom.PumpMessages()


def OnEvent(event):
    write_to_file = False
    escape_button_ascii = 27
    enter_buttons = ['\n', '\r']

    if verbose:
        print('#' * 40)

    if 'Wheel' in dir(event):
        if verbose:
            print('Mouse Event')
        return True
    else:
        if event.Ascii == escape_button_ascii:
            sys.exit()

        if verbose:
            print('KeyBoard Event')
        write_to_file = True

    if verbose:        
        print('#' * 40)

    for attr in dir(event):
        if not attr.startswith('__'):
            if verbose:
                print ("obj.%s = %r" % (attr, getattr(event, attr)))

            if write_to_file and attr == 'Ascii':
                if write_to_file and chr(getattr(event, attr)) in string.printable:
                    with open(keylog,'at') as f:
                        f.write(chr(getattr(event, attr)))
                        if chr(getattr(event, attr)) in enter_buttons:
                             f.write(str(datetime.datetime.now()))
                             f.write(":\t")

    # return True to pass the event to other handlers
    return True


def start_key_logger(keyboard=True, mouse=False):

    # start the log
    with open(keylog,'w') as f:
        f.write(str(datetime.datetime.now()))
        f.write(":\t")

    # create a hook manager
    hook_manager = pyHook.HookManager()

    if mouse:
        # watch for all mouse events
        hook_manager.MouseAll = OnEvent
        # set the mouse hook
        hook_manager.HookMouse()

    if keyboard:
        # watch for all keyboard events
        hook_manager.KeyDown = OnEvent
        # set the keybboard hook
        hook_manager.HookKeyboard()

    # wait forever (try except to ignore things like Ctrl+Shift...)
    try:
        pythoncom.PumpMessages()
    except:
        pass

0 个答案:

没有答案