you just OR them together

import ctypes

# buttons
MB_OK = 0x0
MB_OKCXL = 0x01
MB_YESNOCXL = 0x03
MB_YESNO = 0x04
MB_HELP = 0x4000

# icons
ICON_EXCLAIM = 0x30
ICON_INFO = 0x40
ICON_STOP = 0x10

result = ctypes.windll.user32.MessageBoxA(0, "Your text?", "Your title", MB_HELP | MB_YESNO | ICON_STOP)

I got the hex values from the documentation you linked to

Answer from Joran Beasley on Stack Overflow
🌐
Python
docs.python.org › 3 › library › ctypes.html
ctypes — A foreign function library for Python
WINUSERAPI int WINAPI MessageBoxW( HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType); Here is the wrapping with ctypes: >>> from ctypes import c_int, WINFUNCTYPE, windll >>> from ctypes.wintypes import HWND, LPCWSTR, UINT >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT) >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0) >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags) The MessageBox foreign function can now be called in these ways: >>> MessageBox() >>> MessageBox(text="Spam, spam, spam") >>> MessageBox(flags=2, text="foo bar") A second example demonstrates output parameters.
Discussions

arcpy - ArcGIS python script freezes when using ctypes MessageBox - Geographic Information Systems Stack Exchange
I have written a simple ArcGIS python script tool that takes only one input, a file, and displays a "Yes/No" message box when the script is run. The script runs, but the message box pops up behind... More on gis.stackexchange.com
🌐 gis.stackexchange.com
April 22, 2018
Python How to keep MessageboxW on top of all other windows? - Stack Overflow
Context: I have a small script that alerts the user of an event by creating a message box using the Windows in built message box (Ref: MSDN MessageBox) which is imported using ctypes. This script ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to specify what actually happens when Yes/No is clicked with ctypes MessageBoxW? - Stack Overflow
#!/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 _MessageBox... More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
ctypes - How to bring python message box in front? - Stack Overflow
import ctypes from time import ... 0x00001000 ctypes.windll.user32.MessageBoxW(None, "This should be in top", "Very important message", MB_SYSTEMMODAL) I always recommend using .argtypes and .restype to ensure parameters are marshaled correctly between Python and C and it ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › guineawheek › 567500ff9a02be11b671
Using native Windows message boxes in pure python · GitHub
Using native Windows message boxes in pure python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Super User
superuser.com › questions › 1542422 › is-it-possible-to-have-a-ctypes-meassege-box-for-a-python-script-that-is-install
windows 10 - Is it possible to have a ctypes meassege box for a python script that is installed as a NSSM service? - Super User
#!/usr/bin/python3 import os ,sys import time import ctypes def SomeProgram(): if SomeCondition: return True, FilePath def Mbox(title, text, style): return ctypes.windll.user32.MessageBoxW(0, text, title, style) if __name__ == '__main__': while True: WriteToPdf, FilePath = SomeProgram() if WriteToPdf: MboxResult = Mbox('Print?', 'Would you like to print the the file?', 4) if MboxResult==6: #Yes was selected.
🌐
Mfcallahan
mfcallahan.com › 2022 › 11 › 10 › display-a-message-box-with-python-without-using-a-library-or-other-dependency-windows
Display a message box with Python without using a non-standard library or other dependency (Windows)
December 1, 2022 - This will set its z-order so that the message box is on top of all other open windows. The ctypes library exposes methods which essentially wrap up calls to the Windows API functions like MessageBoxExW, making interacting with the API easy.
🌐
Stack Exchange
gis.stackexchange.com › questions › 280411 › arcgis-python-script-freezes-when-using-ctypes-messagebox
arcpy - ArcGIS python script freezes when using ctypes MessageBox - Geographic Information Systems Stack Exchange
April 22, 2018 - import arcpy import ctypes inFile = arcpy.GetParameterAsText(0) arcpy.AddMessage("\nInput file: {0}\n".format(inFile)) # Yes/No mbox = 4, return code Yes = 6, return code No = 7 mBox = ctypes.windll.user32.MessageBoxW result = mBox(None, u"Just checking...", u"File Check", 4) if result == 6: arcpy.AddMessage("User pressed Yes\n") elif result == 7: arcpy.AddMessage("User pressed No\n") else: arcpy.AddMessage("Unknown return code\n") arcpy.AddMessage("Complete.\n")
Find elsewhere
Top answer
1 of 4
7

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

if __name__ == "__main__":
    main()

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

2 of 4
3

Quoting official docs:

Return value

Type: int

If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect. If the function fails, the return value is zero. To get extended error information, call GetLastError. If the function succeeds, the return value is one of the following menu-item values

You may checked listed values under official docs link.

Sample code would be something like:

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
🌐
Blogger
techietrivia.blogspot.com › 2012 › 07 › python-message-box-in-windows.html
TRIVIA: Python: Message Box in Windows
July 13, 2012 - Example 2: Message Box with OK-Cancel button & ReturnValue Check import ctypes · messageBox = ctypes.windll.user32.MessageBoxW returnValue = messageBox(None,"Message Box!!!","Hello",0x40 | 0x1) if returnValue = = 1: print("Pressed OK") elif returnValue = = 2: print("Pressed Cancel")
🌐
Stack Overflow
stackoverflow.com › questions › 69920992 › using-ctypes-for-a-message-box-in-python
popup - Using ctypes for a message box in Python - Stack Overflow
November 10, 2021 - import ctypes # An included library with Python install. def message(title, message, style): ctypes.windll.user32.MessageBoxW(0, message, title, style)
Top answer
1 of 2
2

If you want a simple solution, use the PyMsgBox module. It uses Python's built-in tkinter library to create message boxes, including ones that let the user type a response. Install it with pip install pymsgbox.

The documentation is here: https://pymsgbox.readthedocs.org/

The code you want is:

>>> import pymsgbox
>>> returnValue = pymsgbox.prompt('Message box!', 'Title')
2 of 2
0

Message box is for messages only. What you need is QDialog. You can create it in QtDesigner(I have login dialog created this way, with 2 QLineEdit for username and pass, 2 buttons in QDialogButtonBox and QCombobox for language choose). You'll get .ui file, which you'll need to convert into .py this way in cmd:

pyuic4 -x YourLoginDialogWindow.ui -o YourLoginDialogWindow.py

import created YourLoginDialogWindow.py and you can use it and implement any method you need:

import YourLoginDialogWindow

class YourLoginDialog(QtGui.QDialog):
    def __init__(self, parent = None):
        super(YourLoginDialog, self).__init__(parent)
        self.__ui = YourLoginDialogWindow.Ui_Dialog()
        self.__ui.setupUi(self)
        ...
        self.__ui.buttonBox.accepted.connect(self.CheckUserCredentials)
        self.__ui.buttonBox.rejected.connect(self.reject)

    def GetUsername(self):
        return self.__ui.usernameLineEdit.text()

    def GetUserPass(self):
        return self.__ui.passwordLineEdit.text()

    def CheckUserCredentials(self):
        #check if user and pass are ok here
        #you can use self.GetUsername() and self.GetUserPass() to get them
        if THEY_ARE_OK :
            self.accept()# this will close dialog and open YourMainProgram in main
        else:# message box to inform user that username or password are incorect
            QtGui.QMessageBox.about(self,'MESSAGE_APPLICATION_TITLE_STR', 'MESSAGE_WRONG_USERNAM_OR_PASSWORD_STR')

in your __main__ first create login dialog and then your main window...

if __name__ == "__main__":
    qtApp = QtGui.QApplication(sys.argv)

    loginDlg = YourLoginDialog.YourLoginDialog()
    if (not loginDlg.exec_()):
        sys.exit(-1)

    theApp = YourMainProgram.YourMainProgram( loginDlg.GetUsername(), loginDlg.GetPassword())
    qtApp.setActiveWindow(theApp)
    theApp.show()
    sys.exit(qtApp.exec_())
🌐
Stack Overflow
stackoverflow.com › questions › 34953438 › how-can-i-get-the-value-of-the-pressed-button-inside-of-a-ctypes-messageboxa
python - How can I get the value of the pressed button inside of a ctypes MessageBoxA? - Stack Overflow
January 23, 2016 - def close_program(self, evt): # ctypes messagebox return values MB_OK = 0 MB_OKCANCEL = 1 MB_YESNOCANCEL = 3 MB_YESNO = 4 IDOK = 0 IDCANCEL = 2 IDABORT = 3 IDYES = 6 IDNO = 7 resp = ctypes.windll.user32.MessageBoxA(0, "Are you sure?", "Alert!", 4) if resp == IDYES: sys.exit(0) else: pass
🌐
Python
bugs.python.org › issue16691
Issue 16691: How to use ctypes.windll.user32.MessageBoxW - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/60895
🌐
Stack Overflow
stackoverflow.com › questions › 44347891 › how-can-i-check-the-input-from-a-message-boxs-buttons-in-python-using-the-ctype
How can I check the input from a message box's buttons in Python using the ctypes library? - Stack Overflow
You can find the numerical values in the MessageBox function · import ctypes class MbConstants: MB_OKCANCEL = 1 IDCANCEL = 2 IDOK = 1 def mbox(message, title): return ctypes.windll.user32.MessageBoxW(0,message, title, MbConstants.MB_OKCANCEL) rc = mbox("message","title") if rc == MbConstants.IDOK: print("ok") elif rc == MbConstants.IDCANCEL: print("cancel")
🌐
Microsoft Learn
learn.microsoft.com › en-us › windows › win32 › api › winuser › nf-winuser-messageboxw
MessageBoxW function (winuser.h) - Win32 apps | Microsoft Learn
February 8, 2023 - int DisplayResourceNAMessageBox() { int msgboxID = MessageBox( NULL, (LPCWSTR)L"Resource not available\nDo you want to try again?", (LPCWSTR)L"Account Details", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2 ); switch (msgboxID) { case IDCANCEL: // TODO: add code break; case IDTRYAGAIN: // TODO: add code break; case IDCONTINUE: // TODO: add code break; } return msgboxID; }