如何指定使用 ctypes MessageBoxW 单击是/否时实际发生的情况?

新手上路,请多包涵
def addnewunit(title, text, style):
    ctypes.windll.user32.MessageBoxW(0, text, title, style)

我看到很多人展示了这段代码,但是没有人具体说明如何使 Yes/No 生效。它们是按钮,它们就在那里,但是如何指定单击 或 时实际发生的情况?

原文由 Ryan Mansuri 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 831
2 个回答

像这样使用适当的 ctypes 包装的东西:

 #!/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:\n{}".format(win_err))

if __name__ == "__main__":
    main()

有关 utype 参数的各种值,请参阅 MessageBox 的文档

原文由 Neitsa 发布,翻译遵循 CC BY-SA 4.0 许可协议

引用 官方文档

返回值

类型:整数

如果消息框有一个取消按钮,如果按下 ESC 键或选择取消按钮,该函数将返回 IDCANCEL 值。如果消息框没有取消按钮,则按 ESC 键无效。 如果函数失败,则返回值为零。 要获取扩展的错误信息,请调用 GetLastError。 如果函数成功,返回值是以下菜单项值之一

您可以在官方文档链接下查看列出的值。

示例代码类似于:

 def addnewunit(title, text, style):
    ret_val = ctypes.windll.user32.MessageBoxW(0, text, title, style)
    if ret_val == 0:
        raise Exception('Oops')
    elif ret_val == 1:
        print "OK Clicked"
    ...  # additional conditional checks of ret_val may go here

原文由 Łukasz Rogalski 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题