July 2002
Intermediate to advanced
608 pages
15h 46m
English
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 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:
def OnQuit(self):
if areYouSure( ):
win32event.SetEvent(StopEvent) # Exit msg pump
def _MessagePump( ):
waitables = StopEvent, OtherEvent
while 1:
rc = win32event.MsgWaitForMultipleObjects(
waitables,
0, # Wait for all = false, so it waits for anyone
TIMEOUT, # (or win32event.INFINITE)
win32event.QS_ALLEVENTS) # Accepts all input # You can call a function here, if it doesn't take too long. It will # be executed at least every 200ms -- 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 break elif rc == win32event.WAIT_OBJECT_0+1: # Our second event listed, "OtherEvent", was set. Do whatever needs # to be done -- you can wait on as many kernel-waitable objects as # needed (events, locks, processes, threads, notifications, and so on). pass elif rc == win32event.WAIT_OBJECT_0+len(waitables): ...Read now
Unlock full access