Click here to Skip to main content
15,867,568 members
Articles / Desktop Programming / MFC
Article

TCX Message Box (derived from CWnd)

Rate me:
Please Sign up or sign in to vote.
4.78/5 (14 votes)
18 Nov 19997 min read 172.7K   3.1K   55   23
An extended message box class for MFC applications.

Sample Image

Introduction

Here I present an extended message box class for MFC applications (CTcxMsgBox). It's an attempt to improve a couple of limitations of the regular API provided message box.

First, thanks to my friend Christian M. Garbin, who suggested I should prefix my classes with my initials. Uh, I really haven't thought that before.

With a CTcxMsgBox, you can:

  • Customize the buttons. You can choose as many buttons as you need, and you can give them whatever command ID and title you want. Therefore, you're not restrained to the old Abort/Retry/Ignore,OK, OK/Cancel, Retry/Cancel, Yes/No, Yes/No/Cancel schemas.
  • Select the default and the escape button.
  • Select any icon to decorate the message.
  • Display messages in Rich Text Format. Therefore, you can format your important messages to really grab user's attention to what's important.

For example, the sample image is a snapshot of the message box created by the following code:

static const LPCTSTR _pMsg =
    "{\\rtf1\\ansi\\deff0\\deftab720{\\fonttbl{\\f0\\"
    "fswiss MS Sans Serif;}{\\f1\\froman\\fcharset2 Symbol;}"
    "{\\f2\\froman Times New Roman;}{\\f3\\"
    "froman Times New Roman;}{\\f4\\fswiss\\fprq2 Arial;}}"
    "{\\colortbl\\red0\\green0\\blue0;}"
    "\\deflang1046\\pard\\plain\\f4\\fs20 "
    "What about a Message Box with the following features?"
    "\\par \\pard\\li360\\fi-360{\\*\\pn\\pnlvlblt\\pnf1\\"
    "pnindent360{\\pntxtb\\'b7}}\\plain\\f4\\fs20\\b "
    "{\\pntext\\f1\\'b7\\tab}R\\plain\\f4\\fs20\\i ich "
    "\\plain\\f4\\fs20\\b T\\plain\\f4\\fs20\\i ext \\plain"
    "\\f4\\fs20\\b F\\plain\\f4\\fs20\\i ormat\\plain\\f4\\fs20"
    "  support;\\plain\\f2\\fs20 "
    "\\par \\plain\\f4\\fs20 {\\pntext\\f1\\'b7\\tab}"
    "Automatic layout calculation for best size;\\plain\\f2\\fs20 "
    "\\par \\plain\\f4\\fs20 {\\pntext\\f1\\'b7\\tab}Customizeable"
    " \\plain\\f4\\fs20\\b Buttons\\plain\\f4\\fs20 ;\\plain\\f2\\fs20 "
    "\\par \\plain\\f4\\fs20 {\\pntext\\f1\\'b7\\tab}Customizeable"
    " \\plain\\f4\\fs20\\b Icon\\plain\\f4\\fs20 ;\\plain\\f2\\fs20 "
    "\\par \\plain\\f4\\fs20 {\\pntext\\f1\\'b7\\tab}Customizeable"
    " \\plain\\f4\\fs20\\b Title\\plain\\f4\\fs20 ;\\plain\\f2\\fs20 "
    "\\par \\pard\\plain\\f4\\fs20 "
    "\\par Wouldn't that be really \\plain\\f4\\fs28\\b\\i \"cool\" \\"
    "plain\\f4\\fs20 ?\\plain\\f2\\fs20 "
    "\\par }";

    CTcxMsgBox msg( this );

    msg.SetTitle( IDS_TITLE3 );
    msg.SetRtf();
    msg.SetMsg( _pMsg );
    msg.SetIcon( IDI_THUMB );

    msg.AddButton( IDC_YEAH, TRUE, FALSE );
    msg.AddButton( IDC_YES, FALSE, FALSE );
    msg.AddButton( IDC_MAYBE, FALSE, FALSE );

    msg.DoModal();

To create _pMsg string, I simply edited a RTF file with Microsoft's Wordpad, and opened it as plain text file in VC++. After that, I copied it to the C++ code, not forgetting to replace all the backslashes for double-backslashes (C/C++ syntax for constant strings).

Well, I could have used Microsoft's Word instead of Wordpad. But, as far as I could see, Word puts a lot of default "framing" information in the file, even an empty file, that just makes it bigger, but have no effect over the visual aspect of the RFT data. Wordpad, for its turn, gives us smaller data for the same result.

Another aspect of using RTF is that the messages get bigger - mostly due to all the format information. Therefore, sometimes even a small message with lots of formatting won't fit in a single string slot of the resource's string table (each slot is limited to 512 UNICODE characters).

If the message RTF data is this large, one solution for this problem is to split the message in different parts and glue them all together in a CString object, before calling CTcxMsgBox.

Another solution is to use a CTcxMsgBox's mechanism that allows you to save messages as custom resources. Custom resources are basically binary data that are saved in the resources section. Just create a custom resource type, and one resource of this type for each message. Then, just "paste" the message RTF data on the resource, and save it as binary. The Demo Application makes use of this mechanism.

Another feature that makes life easier are all the FormatMsgXXX member functions. They're similar to CString::Format, so you don't have to create a CString and format it outside the message box. It does it for you.


Member functions

CTcxMsgBox( CWnd* pParentWnd = NULL )

Constructs a CTcxMsgBox object.

virtual ~CTcxMsgBox( void )

Destroys the object.

int DoModal( void )

Like CDialog::DoModal, this function displays the message box in modal mode (the only one allowed). The function waits in the modal loop until the user presses a button or dismisses the window by either closing it or pressing the ESC key. Then, the function returns the code of the command that was used to dismiss the message box.

void AddButton( UINT uIDC, BOOL bIsDefault, BOOL bIsEscape, LPCTSTR pszText )

void AddButton( UINT uIDC, BOOL bIsDefault, BOOL bIsEscape, UINT uIdText = (UINT)-1 )

Adds a custom button to the message box. Buttons must be added in the sequence they will appear, from left to right. Parameter uIDC is the button's command ID (e.g. IDOK). Parameter bIsDefault sets this button as the default button, and overrides any previous added button that used this style. Parameter bIsEscape sets this buttons as the escape button. Therefore, this button's command ID will be returned if the user either closes the window or presses the ESC key. If no button is set as the escape button, the message box won't have the titles bar's close button, neither will it be dismissed by the ESC key. Parameter pszText points to a string to title the button. Parameter uIdText identifies a string, in the resource's string table, to title the button.

void SetTitle( LPCTSTR pszTitle )

void SetTitle( UINT uIdTitle )

Set the message box title. The default title, if this function is not used, is the application name (AfxGetApp()->m_pszAppName). The parameters are obvious.

void SetRtf( BOOL bRtf = TRUE )

Sets the message box to work in RTF mode. The default mode after construction is "RTF OFF". If the RTF is inactive, the object will work with messages as plain texts. The parameter is obvious.

BOOL SetMsg( UINT uMsgId )

BOOL SetMsg( LPCTSTR pszMsg )

Set the message to be displayed. The parameters are obvious.

BOOL SetMsgEx( LPCTSTR pszMsgResId, LPCTSTR pszMsgResType )

Loads the message from a custom type resource. Parameter pszMsgResId is the resource ID. If it's a UINT resource ID, use the MAKEINTRESOURCE to convert it to a LPCTSTR. Parameter pszMsgResType is the resource type. The Demo Application has several samples of using this mechanism.

BOOL FormatMsg( LPCTSTR pszFmt, ... )

BOOL FormatMsg( UINT uFmtStrId, ... )

Format the message to be displayed. See CString::Format for more information.

BOOL FormatMsgEx( LPCTSTR pszMsgResId, LPCTSTR pszMsgResType, ... )

Same as above. The only difference is that the formatting string is loaded from a custom resource.

BOOL FormatMsgV( LPCTSTR pszFmt, va_list marker )

See C/C++ runtime library's vsprintf for details of this kind of construction.

void SetIcon( HICON hIcon )

void SetIcon( UINT uIcon )

Sets the icon to be displayed. If no icon is set, there'll be no icon in the message box. Well, that's pretty obvious. It's just to let you know that I don't put any undesired icon in that place :).

void SetStandardIcon( LPCTSTR pszIconName )

Sets the icon to be displayed. The icon is one of the standard icons (IDI_APPLICATION, IDI_HAND, IDI_QUESTION, IDI_EXCLAMATION, IDI_ASTERISK). For more details, see CWinApp::LoadStandardIcon.

void SetMetric( int iMetric, int xy )

int GetMetric( int iMetric )

These functions are intended to advance use only. You can change some metrics of the message box, like borders, gaps, etc. Parameter iMetric is the metric index. See the header file for the metric indexes enumeration.


Final notes

Remember that message boxes are not a solution, but an anomaly of the UI universe. A cool UI should use as few message boxes as possible. However, sometimes it's just that we don't have the time or resources to design that cute ultimate smooth UI, and we finish using message boxes now and then.

One good thing about the CTcxMsgBox is that you can make your messages to really look different, so improving the chances you'll grab user attention to what's really important or catastrophic. Therefore, the risks a user will mistake an important message, thus giving it a wrong order, by other he/she always gets in her/his way are lower.

For example, look at the following snapshots. The first is a regular VC++ message box. The second is a "replacement" with CTcxMsgBox. Note how it really highlights the important information. If the user never saw this message before, he/she would stop and pay attention to it. Besides, due to the visual cues, experienced users can extract the important information quicker.

Figure 2

Figure 3

I hope you really enjoy this class. Even better, I hope you make good use of it - let me know by then. And sorry for my not so wonderful English. This is not my first language, and besides I can write good enough English, I generally demand some energy to do that. But that would mean I would never have the time to write a good documentation, and to deploy the code. Therefore, I choose to be a little bit loose with the writing, but to give you the good code anyway.


Files to include

The only files you need to include in you project are:

  • TcxMsgBox.h - the header file
  • TcxMsgBox.cpp - the code file

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralDifferent background color for MessageBox and Buttons Pin
Cyber Friend12-May-07 2:37
Cyber Friend12-May-07 2:37 
QuestionProblem when insert one variable? Pin
Le Khac Chinh16-Feb-04 16:54
Le Khac Chinh16-Feb-04 16:54 
AnswerRe: Problem when insert one variable? Pin
Gil Clark6-Aug-04 9:35
Gil Clark6-Aug-04 9:35 
Generaluiui Pin
Le Khac Chinh16-Feb-04 16:50
Le Khac Chinh16-Feb-04 16:50 
QuestionMicrosoft Web Browser Object into DialogBox, without MFC? Pin
Adrian Bacaianu8-Apr-03 20:49
Adrian Bacaianu8-Apr-03 20:49 
GeneralBug fix for use with WinXP themes Pin
Anna :)3-Dec-02 6:00
Anna :)3-Dec-02 6:00 
GeneralFix For Unicode Pin
13-Feb-02 7:47
suss13-Feb-02 7:47 
In TcxMsgBox.h Add:

#include "Afxpriv.h"

In _LoadStringEx:

replace CString str( (LPCTSTR)pData, dwSize );
with: CString str( (BYTE*)pData );

In CTcxMsgBox::CreateRtfCtrl():

replace es.dwCookie = (DWORD)(LPCTSTR)m_strMsg;
with :
#ifdef _UNICODE
USES_CONVERSION;
es.dwCookie = (DWORD)W2CA((LPCTSTR)m_strMsg);
#else
es.dwCookie = (DWORD)(LPCTSTR)m_strMsg;
#endif
GeneralResource Leaks Pin
Andreas Kuhtz9-Feb-02 23:51
Andreas Kuhtz9-Feb-02 23:51 
GeneralRe: Resource Leaks Pin
WREY28-Feb-04 4:09
WREY28-Feb-04 4:09 
Generalproblem with large messages Pin
Pieter Hilkemeijer2-Jan-02 0:30
Pieter Hilkemeijer2-Jan-02 0:30 
Generalproblem on W2K Pin
peterchen28-Nov-01 2:17
peterchen28-Nov-01 2:17 
GeneralFix for the problem under Windows 2000 Pin
Uwe Keim20-Apr-01 3:19
sitebuilderUwe Keim20-Apr-01 3:19 
GeneralRe: Fix for the problem under Windows 2000 Pin
WREY28-Feb-04 4:01
WREY28-Feb-04 4:01 
GeneralAdding autodestroy capability Pin
Alex Lewandowski30-Mar-01 3:50
Alex Lewandowski30-Mar-01 3:50 
QuestionPrinting the contents ? Pin
mkalman@zenonbio.hu25-Oct-00 5:52
mkalman@zenonbio.hu25-Oct-00 5:52 
GeneralHTML is less wordy than RTF, so... Pin
Andy Metcalfe10-Sep-00 19:21
sussAndy Metcalfe10-Sep-00 19:21 
GeneralRe: HTML is less wordy than RTF, so... Pin
Thales P. Carvalho11-Sep-00 2:11
Thales P. Carvalho11-Sep-00 2:11 
GeneralRe: HTML is less wordy than RTF, so... Pin
Anna-Jayne Metcalfe29-Jan-02 22:40
Anna-Jayne Metcalfe29-Jan-02 22:40 
GeneralRe: HTML is less wordy than RTF, so... Pin
13-Mar-02 11:07
suss13-Mar-02 11:07 
GeneralRe: HTML is less wordy than RTF, so... Pin
Anna :)3-Dec-02 3:59
Anna :)3-Dec-02 3:59 
GeneralRe: HTML is less wordy than RTF, so... Pin
DanCooperstock12-May-09 15:53
DanCooperstock12-May-09 15:53 
GeneralFIX for Windows 2000 Pin
Harold Harkema26-Feb-00 5:00
sussHarold Harkema26-Feb-00 5:00 
GeneralRe: FIX for Windows 2000 Pin
WREY28-Feb-04 4:04
WREY28-Feb-04 4:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.