Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - How to specify what actually happens when Yes/No is clicked with ctypes MessageBoxW?

def addnewunit(title, text, style):
    ctypes.windll.user32.MessageBoxW(0, text, title, style)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this with proper ctypes wrapping:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes
from ctypes.wintypes import HWND, LPWSTR, UINT

_user32 = ctypes.WinDLL('user32', use_last_error=True)

_MessageBoxW = _user32.MessageBoxW
_MessageBoxW.restype = UINT  # default return type is c_int, this is not required
_MessageBoxW.argtypes = (HWND, LPWSTR, LPWSTR, UINT)

MB_OK = 0
MB_OKCANCEL = 1
MB_YESNOCANCEL = 3
MB_YESNO = 4

IDOK = 1
IDCANCEL = 2
IDABORT = 3
IDYES = 6
IDNO = 7


def MessageBoxW(hwnd, text, caption, utype):
    result = _MessageBoxW(hwnd, text, caption, utype)
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return result


def main():
    try:
        result = MessageBoxW(None, "text", "caption", MB_YESNOCANCEL)
        if result == IDYES:
            print("user pressed ok")
        elif result == IDNO:
            print("user pressed no")
        elif result == IDCANCEL:
            print("user pressed cancel")
        else:
            print("unknown return code")
    except WindowsError as win_err:
        print("An error occurred:
{}".format(win_err))

if __name__ == "__main__":
    main()

See the documentation for MessageBox for the various value of the utype argument.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...