How to get user input from buttons on pop up (ctypes)

Question:

So I’ve made a messagebox using ctypes to close my program:

def kill():
ctypes.windll.user32.MessageBoxW(0, "Thanks for using Chatbot", "Chatbot", 1)
sys.exit()

but I’m not sure how to get the user input when they click either "ok" or "cancel", I want cancel to not close the program.

Asked By: Mystik

||

Answers:

Capture the return value. It’s also good practice to define .argtypes and .restype.

import ctypes
import ctypes.wintypes as w

# From the documentation at
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw
MB_OKCANCEL = 1
IDCANCEL = 2
IDOK = 1

user32 = ctypes.WinDLL('user32')
MessageBox = user32.MessageBoxW
MessageBox.argtypes = w.HWND, w.LPCWSTR, w.LPCWSTR, w.UINT
MessageBox.restype = ctypes.c_int

ret = MessageBox(None, 'message', 'title', MB_OKCANCEL)
if ret == IDOK:
    print('OK')
elif ret == IDCANCEL:
    print('CANCEL')
else:
    print(f'{ret=}')
Answered By: Mark Tolonen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.