Skip to content

Instantly share code, notes, and snippets.

@NateScarlet
Last active May 25, 2021 05:53
Show Gist options
  • Save NateScarlet/8012ea3ac277aab5c9b75e8ea139f495 to your computer and use it in GitHub Desktop.
Save NateScarlet/8012ea3ac277aab5c9b75e8ea139f495 to your computer and use it in GitHub Desktop.
pywin32 cancelable message box
import msvcrt
import threading
import time
from typing import Callable, Set, Text
import win32con
import win32gui
def message_box(
msg: Text,
caption: Text,
*,
flags: int = 0,
h_wnd: int = 0,
on_close: Callable[[], None] = None,
) -> Callable[[], None]:
def _run():
win32gui.MessageBox(h_wnd, msg, caption, flags)
if callable(on_close):
on_close()
t = threading.Thread(target=_run)
t.start()
h_wnd_set: Set[int] = set()
def _iter_window(h_wnd, _):
if win32gui.GetClassName(h_wnd) != "#32770": # message box
return
h_wnd_set.add(h_wnd)
while not h_wnd_set:
time.sleep(0.01)
win32gui.EnumThreadWindows(t.ident, _iter_window, None)
assert len(h_wnd_set) == 1, h_wnd_set
def _close():
for i in h_wnd_set:
if win32gui.IsWindow(i):
win32gui.PostMessage(i, win32con.WM_CLOSE, 0, 0)
t.join()
return _close
if __name__ == '__main__':
close = message_box(
"message", "caption",
h_wnd=win32gui.FindWindow("CabinetWClass", None),
on_close=lambda: print("close"),
)
print("Press any key")
msvcrt.getch()
close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment