pythoncom.PumpMessages()

From what I understand this line basically tells the program to wait forever. For my purposes it seems to be working. However, I'd like to be able to end the program given the right stimulus. How would one go about ending the above line, or stopping the program from running any further.


Solution 1:

According to these docs, pythoncom.PumpMessages():

Pumps all messages for the current thread until a WM_QUIT message.

So one way to stop collecting messages is by posting a WM_QUIT message to the message queue by using the ctypes library to call PostQuitMessage:

ctypes.windll.user32.PostQuitMessage(0)

Solution 2:

Here's an example of quitting the app using a timer thread:

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() will work only from the main thread, but then again the main thread is blocked, so it's not very useful by itself. You can only use it if you hook your own custom message handling into the message loop.