0

我使用挂钩来检查鼠标事件和键盘事件,并为挂钩创建一个新线程,因为我还有其他工作要做。

钩子线程一直在消耗CPU,所以我想偶尔暂停一下(为了效率)。我尝试使用 PostQuitMessage() 来停止它,然后等待在正确的时间重新启动线程和 PumpMessages()。但它不起作用。

我期待收到您的答复!

以下是代码的主要部分,您可以运行它然后会遇到问题。附言。原谅我的英语不好~_~

# -*- coding: utf-8 -*- #
#Python version:3.5.4
from win32 import win32process
import time
import threading
#import win32
import psutil
import PyHook3 as pyHook
import pythoncom
import win32gui, win32ui, win32con, win32api

def OnMouseEvent(event):
    print('-----Mouse-----', event)
    return True
def OnKeyboardEvent(event):
    print('-----key-----', event)
    if str(event.Key)=='F12':   
        win32api.PostQuitMessage()
    return True

def InputScan():
    print('-----InputScan-----')
    hm.MouseLeftDown = OnMouseEvent
    hm.HookMouse()
    hm.KeyDown = OnKeyboardEvent
    hm.HookKeyboard()
    #first time is worked normally,but re-execution not working
    pythoncom.PumpMessages() 
    return True


print('start program...')
threads = []
nowThreadsName=[]
hm = pyHook.HookManager()
try:
    ThreadIS = threading.Thread(target=InputScan, name='ThreadIS', args=())
    ThreadIS.setDaemon(True)
    threads.append(ThreadIS)
    ThreadIS.start()
except:
    print("Error:--")
while 1:
    #some other works
    time.sleep(5)
    open_str = input("whether restart(anykey): \n")
    nowthread = threading.enumerate()
    nowThreadsName.clear()
    print("nowThreadsNameclear=",nowThreadsName)
    for i in nowthread:
        nowThreadsName.append(i.getName())
    print("nowThreadsName=",nowThreadsName)
    if 'ThreadIS' in nowThreadsName:
        pass
    else:
        t = threading.Thread(target=InputScan, name='ThreadIS', args=())
        t.setDaemon(True)
        t.start() #why it dosen't work??
        pass
    pass
4

0 回答 0