AfxMessageBox

MessageBoxes are simple and effective way of showing errors on input/processing or outputs. They can be used intuitively to communicate the messages in a very clear cut fashion. They can be used to provide 3 kinds of messages. The message can be either an Information, Question or a Warning.

Messagebox es’ can be useful in various places. They can be used inside an MFC application with a window or without a window too. This article discusses how to use message boxes in such different circumstances.

MessageBox in an MFC Application:

This is by far the easiest in an MFC application. It is enough to just pass the message to be displayed and the MessageBox is ready to go. This can be used inside any CWnd derived class in an MFC application.

MessageBox("Text for the MessageBox");

AfxMessageBox for a non-CWnd based class:

The MessageBox function can be replaced with an AfxMessageBox function in any non-window classes. This can even be called inside a console application provided, it includes the necessary headers and libraries required for MFC.

AfxMessageBox ("Test Message from AfxMessageBox function");

Though showing such a simple message is a very easy task for the programmer, it is not advisable in any standard programs. A MessageBox should always include a Title and an Icon to display the type of message.

AfxMessageBox with Icons:

When icons are combined with messages in a mesagebox the meanings to the user can be very clear. For example to inform the user “An upload operation is complete”, the following function would be appropriate.

AfxMessageBox ("An upload operation is complete!",MB_ICONINFORMATION|MB_OK);

The above message will really serve the purpose of communicating an information. In case the user has selected an invalid item or a wrong button had been clicked, the following can be an appropriate message.

AfxMessageBox ("Wrong button clicked!",MB_ICONQUESTION|MB_OK);

Some more useful icons can be MB_ICONWARNING, MB_ICONSTOP etc.,

AfxMessgeBox with return values:

Sometimes the message boxes might need to take action based on the replies through message boxes. An example is as follows.

int nResult = CWnd.MessageBox("Are you Sure to quit?", MB_YESNO|MB_ICONQUESTION);

if(nResult == IDYES)
{
   //Quit
}
else
{

  //Stay

}

Thus if these cute little boxes are used with some extra options, they can add a lot of value to the applications.