Wednesday 17 August 2011

Message Box with custom commit buttons

Windows API and MFC framework offer ready to use Message Box dialog which can display, depending on a provided flag, one or group of more commit buttons with captions from a predefined set: OK, Yes, No, Cancel, Abort, Retry and Ignore. If dialog contains a question, it is a good practice to make buttons displaying specific responses, e.g. "Run" - "Don't run", "Apply" - "Don't apply" etc. The easiest and quickest way to achieve this is to create a new, custom dialog and add onto it buttons with desired text. Resource editor in Visual Studio creates by default dialog with two buttons, OK and Cancel and you can rename them, providing that new captions will match OK and Cancel functionality. For other buttons, add BN_CLICKED handlers (ON_BN_CLICKED entry in message map). The purpose of this dialog is just to pick the user's answer on a question and not to do any hard work. Caller should read return value of (custom) Message Box and take further actions depending on it.

Return value of the standard message box (one from a predefined set IDOK, IDYES, ...) identifies user's choice and we can return these predefined values or our custom return codes, e.g. ID_RUN, ID_APPLY...We can also reuse resource ID values of our custom buttons for this purpose. Standard Message Box is a modal dialog so our dialog needs to be created as modal (CDialog::DoModal). DoModal returns value that was passed to CDialog::EndDialog. This function should be called in our custom button BN_CLICKED handlers.

In the following example, our custom Message Box has button "Apply". Its BN_CLICKED handler is OnBnClickedButtonApply. Caller identifies user's choice with DoModal return value:

Our Message Box which has "Apply" button:


No comments: