Credit: Michael Robin
In a Win32 application, you need to process messages, but you also want to wait for kernel-level waitable objects, and coordinate several activities.
A Windows application's message loop, also known as its message pump, is at the heart of Windows. It's worth some effort to ensure that the heart beats properly and regularly:
import win32event import pythoncom TIMEOUT = 200 # ms StopEvent = win32event.CreateEvent(None, 0, 0, None) OtherEvent = win32event.CreateEvent(None, 0, 0, None) class myCoolApp(object): def OnQuit(self): # assume 'areYouSure' is a global function that makes a final # check via a message box, a fancy dialog, or whatever else! if areYouSure( ): win32event.SetEvent(StopEvent) # Exit msg pump def _MessagePump( ): waitables = StopEvent, OtherEvent while True:rc = win32event.MsgWaitForMultipleObjects( waitables, , # Wait for all = false, so it waits for any one TIMEOUT, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accept all kinds of events # You can call a function here, if it doesn't take too long. It will # be executed at least every TIMEOUT ms -- possibly a lot more often, # depending on the number of Windows messages received. if rc == win32event.WAIT_OBJECT_0: # Our first event listed, the StopEvent, was triggered, so # we must exit, terminating the message pump break elif rc == win32event.WAIT_OBJECT_0+1: # Our second event listed, "OtherEvent", ...