JavaScript
x
3
1
def addnewunit(title, text, style):
2
ctypes.windll.user32.MessageBoxW(0, text, title, style)
3
Ive seen a lot of people show this code, however nobody has ever specified how to actually make the Yes/No work. Theyre buttons, and they are there, however how does one specify what actually happens when you click either or?
Advertisement
Answer
Something like this with proper ctypes wrapping:
JavaScript
1
47
47
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
import ctypes
4
from ctypes.wintypes import HWND, LPWSTR, UINT
5
6
_user32 = ctypes.WinDLL('user32', use_last_error=True)
7
8
_MessageBoxW = _user32.MessageBoxW
9
_MessageBoxW.restype = UINT # default return type is c_int, this is not required
10
_MessageBoxW.argtypes = (HWND, LPWSTR, LPWSTR, UINT)
11
12
MB_OK = 0
13
MB_OKCANCEL = 1
14
MB_YESNOCANCEL = 3
15
MB_YESNO = 4
16
17
IDOK = 1
18
IDCANCEL = 2
19
IDABORT = 3
20
IDYES = 6
21
IDNO = 7
22
23
24
def MessageBoxW(hwnd, text, caption, utype):
25
result = _MessageBoxW(hwnd, text, caption, utype)
26
if not result:
27
raise ctypes.WinError(ctypes.get_last_error())
28
return result
29
30
31
def main():
32
try:
33
result = MessageBoxW(None, "text", "caption", MB_YESNOCANCEL)
34
if result == IDYES:
35
print("user pressed ok")
36
elif result == IDNO:
37
print("user pressed no")
38
elif result == IDCANCEL:
39
print("user pressed cancel")
40
else:
41
print("unknown return code")
42
except WindowsError as win_err:
43
print("An error occurred:n{}".format(win_err))
44
45
if __name__ == "__main__":
46
main()
47
See the documentation for MessageBox for the various value of the utype argument.