Sometimes the only user interface you need is a message box. Maybe you just need to alert the user to the completion of a process; or maybe you need to ask a question to which the user responds Yes or No. You'd rather not resort to a console window; but neither do you want to load an entire GUI library to display a simple message box. "Dave", you say, "there must be a better way."
Indeed, there is. Use the DL library to call the MessageBoxA Windows API function.
First, require the dl library:
require 'dl'
We'll feed the function our message text, a dialog box title, and an integer that defines what buttons to display. Let's define some meaningful constants to represent the possible button values:
BUTTONS_OK = 0
BUTTONS_OKCANCEL = 1
BUTTONS_ABORTRETRYIGNORE = 2
BUTTONS_YESNO = 4
The function will return an integer representing the button that the user clicked, so let's define some meaningful constants to represent the possible return code values:
CLICKED_OK = 1
CLICKED_CANCEL = 2
CLICKED_ABORT = 3
CLICKED_RETRY = 4
CLICKED_IGNORE = 5
CLICKED_YES = 6
CLICKED_NO = 7
Here's our method to call the MessageBoxA function from the user32 DLL:
def message_box(txt='', title='', buttons=0)
user32 = DL.dlopen('user32')
msgbox = user32['MessageBoxA', 'ILSSI']
r, rs = msgbox.call(0, txt, title, buttons)
return r
end
Here's how we call it display a message box with an OK button:
message_box("Hello, World!", "Hi!", BUTTONS_OK)
Here's how we call it to display a message box with 'Yes' and 'No' buttons, and process the response:
response = message_box("Are you sure you want to proceed?", "Proceed?", BUTTONS_YESNO)
if response == CLICKED_YES
# insert your code here
end
Finally, here it is in its entirety:
require 'dl'
# button constants
BUTTONS_OK = 0
BUTTONS_OKCANCEL = 1
BUTTONS_ABORTRETRYIGNORE = 2
BUTTONS_YESNO = 4
# return code constants
CLICKED_OK = 1
CLICKED_CANCEL = 2
CLICKED_ABORT = 3
CLICKED_RETRY = 4
CLICKED_IGNORE = 5
CLICKED_YES = 6
CLICKED_NO = 7
def message_box(txt, title=APP_TITLE, buttons=BUTTONS_OK)
user32 = DL.dlopen('user32')
msgbox = user32['MessageBoxA', 'ILSSI']
r, rs = msgbox.call(0, txt, title, buttons)
return r
end
response = message_box("Are you sure you want to proceed?", "Proceed?", BUTTONS_YESNO)
if response == CLICKED_YES
# insert your code here
end
There you have it. As always, let me know if you have questions, comments, or suggestions.
Thanks for stopping by!