中途结束程序
pythoncom.PumpMessages()
根据我的理解,这行代码基本上是让程序一直等待,直到有事情发生。对我来说,这样的效果是可以的。不过,我希望能在合适的情况下结束这个程序。请问怎么才能结束上面这行代码,或者让程序停止继续运行呢?
3 个回答
1
我想补充一下Gregg和Boaz Yaniv的两个回答。通常情况下,你会在一个单独的线程中运行阻塞代码,所以你需要向这个线程发送WM_QUIT消息。正如Gregg提到的,你应该使用PostQuitMessage,但这个方法只在当前线程中有效。你不应该使用PostThreadMessage来发送WM_QUIT消息(我记不清在哪看到过这个说明了)。你可以在讨论中了解更多内容,标题是"为什么有一个特殊的PostQuitMessage函数?"。我认为最好是先向线程发送WM_CLOSE消息。
# if more hotkeys needs to be supported at the same time this class needs to be rewritten
class HotKey:
def __init__(self, modifier_key, virtual_key, callback):
self.hotkey_id = 1
# shared variable to pass thread id
self.pid = mpdummy.Value('l', 0)
# start checking hotkey press in new thread
self.process_pool = mpdummy.Pool()
self.process_pool.apply_async(HotKey.register, (self.hotkey_id, self.pid, modifier_key, virtual_key, callback, ))
self.process_pool.close()
# bind windows global hotkey
@staticmethod
def register(hotkey_id, pid, modifier_key, virtual_key, callback):
# set thread ID to shared variable
# Win API could also be used:
# ctypes.windll.Kernel32.GetCurrentThreadId()
pid.value = mpdummy.current_process().ident
# register hotkey with Win API
logging.getLogger('default').info("Registering hotkey with id " + str(hotkey_id) + " for key " + str(modifier_key) + " " + str(virtual_key))
if not ctypes.windll.user32.RegisterHotKey(None, hotkey_id, modifier_key, virtual_key):
logging.getLogger('default').info("Unable to register hotkey with id " + str(hotkey_id))
msg = ctypes.wintypes.MSG()
try:
# wait for a message - it doesn't return until some message arrives
while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
# WM_HOTKEY 0x0312
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms646279(v=vs.85).aspx
if msg.message == 0x0312:
logging.getLogger('default').info("Pressed hotkey with id " + str(hotkey_id))
callback()
# WM_CLOSE
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms632617(v=vs.85).aspx
elif msg.message == 0x0010:
# quit current thread
# WM_QUIT shouldn't be send with PostThreadMessageA therefore we send WM_CLOSE and quit inside thread.
# More info at:
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms644945(v=vs.85).aspx
# https://blogs.msdn.microsoft.com/oldnewthing/20051104-33/?p=33453
ctypes.windll.user32.PostQuitMessage(0)
ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))
finally:
logging.getLogger('default').info("Unregistering hotkey for id " + str(hotkey_id))
ctypes.windll.user32.UnregisterHotKey(None, hotkey_id)
def unregister(self):
# send WM_CLOSE signal to thread checking for messages
# WM_CLOSE 0x0010
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms632617(v=vs.85).aspx
ctypes.windll.user32.PostThreadMessageA(self.pid.value, 0x0010, 0, 0)
# wait for thread to finish
self.process_pool.join()
我在使用这个功能来注册热键,但原理是一样的。这个类可以这样调用:
# bind global hotkey for "pressing" start/split button
# MOD_ALT 0x0001
# VK_F12 0x7B
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms646309(v=vs.85).aspx
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731.aspx
self.hotkey = hotkey.HotKey(0x0001, 0x7B, self.special_key_pressed)
当你想结束等待消息时,调用:
self.hotkey.unregister()
7
这里有一个使用定时器线程退出应用程序的例子:
import win32api
import win32con
import pythoncom
from threading import Timer
main_thread_id = win32api.GetCurrentThreadId()
def on_timer():
win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);
t = Timer(5.0, on_timer) # Quit after 5 seconds
t.start()
pythoncom.PumpMessages()
PostQuitMessage()
这个函数只能在主线程中使用,但主线程如果被“阻塞”了,就没什么用处了。你只能在把自己的消息处理方式接入消息循环时才能用它。
7
根据这些文档,pythoncom.PumpMessages()
的意思是:
它会处理当前线程的所有消息,直到收到一个WM_QUIT消息为止。
所以,停止接收消息的一种方法是通过使用ctypes库来发送一个WM_QUIT消息到消息队列,这样可以调用PostQuitMessage:
ctypes.windll.user32.PostQuitMessage(0)