I use a hook to check for Mouse Event and Keyboard Event, and I create a new thread for the hook because I have some other work to do.
The hook thread consumes CPU all the time, so I want to pause it occasionally (for efficiency). I tried using PostQuitMessage() to stop it and then wait to restart the thread and PumpMessages() at the right time. but it doesn't work.
I am looking forward to receiving your answers!
The following is the main part of the code,you can run it then will get the problem. ps. Excuse my broken English~_~
# -*- 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