I can't seem to figure out how to let Ctrl-C interrupt this code. It prints a KeyboardInterrupt exception to the console when you press Ctrl-C but never actually stops the program.
How can I make it actually stop?
import ctypes
import ctypes.wintypes
from random import random
user32 = ctypes.windll.user32
ole32 = ctypes.windll.ole32
EVENT_MIN = 0x00000001
EVENT_MAX = 0x7FFFFFFF
def _win_callback(
hWinEventHook: int, event, hwnd, idObject, idChild, idEventThread, dwmsEventTime
):
if random() > 0.95:
print(event)
def loop():
ole32.CoInitializeEx(0)
win_event_proc_type = ctypes.WINFUNCTYPE(
None,
ctypes.wintypes.HANDLE,
ctypes.wintypes.DWORD,
ctypes.wintypes.HWND,
ctypes.wintypes.LONG,
ctypes.wintypes.LONG,
ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD,
)
win_event_proc = win_event_proc_type(_win_callback)
winevent_outofcontext = 0x0000
user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
hook = None
hook = user32.SetWinEventHook(
EVENT_MIN, EVENT_MAX, 0, win_event_proc, 0, 0, winevent_outofcontext,
)
assert hook != 0
msg = ctypes.wintypes.MSG()
print("starting msg loop")
while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
print("msg", msg)
user32.TranslateMessageW(msg)
user32.DispatchMessageW(msg)
if __name__ == "__main__":
loop()
User contributions licensed under CC BY-SA 3.0