Anda di halaman 1dari 11

Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.

htm

Message Boxes
Fundamental Messages Boxes

Overview
A message box is a relatively small dialog box used to display a message and provide one or
more buttons. Here is an example of a message box:

A message box is used to provide information to the user or to request a decision (from the
user). By clicking one of the buttons, the user makes a decision and the program continues.

Message boxes are created from built-in functions from the VCL and the Win32 library. The
necessary functions shipped with the compiler.

Practical Learning: Preparing the Message Boxes Application


1. Create a new project with its starting form
2. Change its Caption to Message Boxes Configuration
3. From the Standard tab of the Component Palette, click the Edit control and click on the form
4. Change the name of the edit control to edtMessage and delete the contents of its Text field.

Message Showing
The ShowMessage() function provides the most fundamental of Borland’s message boxes. This
function takes one string argument and does not return any value. It is used to display a message
to the user who acknowledges it by clicking the OK button. The syntax of the ShowMessage()
function is:

void __fastcall ShowMessage(const AnsiString Message);

A message box created with the ShowMessage() function uses the name of the project as its
caption. The message to display is a string that can be provided by the developer. Here is an
example:

//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonClick(TObject *Sender)
{
ShowMessage("Welcome to the Sellers Bank.");
}
//---------------------------------------------------------------------------

The string can also derive from another control such as the contents of an edit box, a memo, or
any text control. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnMsgFromEditClick(TObject *Sender)
{
ShowMessage(edtMessage->Text);
}
//---------------------------------------------------------------------------

The string can also be a combination of other strings:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
ShowMessage("The name " + AnsiString("\"") +
edtMessage->Text + AnsiString("\"") + " is not in our records.");
}
//---------------------------------------------------------------------------

As with other message boxes that we will study here, to display the message on various lines of
text, you can separate lines using the C/C++ new line constant represented by '\n'. The VCL
provides another alternative. To separate lines of text, you can use the sLineBreak constant. Here
is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AnsiString strMessage = "Your record has been registered";

1 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

AnsiString strCountry = "Country Name: Australia";


AnsiString strCity = "City to visit: Melbourne";
AnsiString strFinal = "Have a nice strip.";

ShowMessage(strMessage + sLineBreak + strCountry + sLineBreak +


strCity + sLineBreak + strFinal);
}
//---------------------------------------------------------------------------

Practical Learning: Using the ShowMessage() Function


1. From the Standard tab of the Component Palette, click Button and click on the form
2. Change the caption of the new button to Show &Msg and change its name to btnShowMsg
3. Double-click the Show Msg button to access its Click event
4. Press Tab and implement it as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnShowMsgClick(TObject *Sender)
{
ShowMessage("Please fill out your Time Sheet before leaving.");
}
//---------------------------------------------------------------------------

5. To test the program, press F9


6. Click the Show Msg button:

7. Click OK and close the form


8. To save the project, on the main menu, click File -> Save All
9. Locate the folder where the exercises are installed
10. Click the Create New folder button. Type Message Boxes and press Enter twice to display the
new folder in the Save In combo box
11. Click Save to save the Unit
12. Type Messages to replace the name of the project and press Enter
13. To display the message on more than one line, change the event as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnShowMsgClick(TObject *Sender)
{
ShowMessage("Please fill out your Time Sheet before leaving.\n"
"Make sure you sign and send it to Human Resources.");
}
//---------------------------------------------------------------------------

14. Test the form to verify the new caption of the message box:
15. And return to Bcb

The Win32 Message Box


The MessageBox() function is derived from Win32. Its syntax is:

int __fastcall MessageBox(const char * Message, const char * Caption, int Flags);

2 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

The MessageBox() function takes three arguments. The first argument, Message, is a
null-terminated string representing the message that the user would read. The Message string
could be a static sentence. It could be constructed from another control. Or it could be a
combination of different strings appended using C/C++ string functions and operations.

You can create a simple message box similar to one implemented using the ShowMessage()
function to display a simple message with an OK button. In this case, you would provide only the
Message argument. Set the other two arguments as NULL. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Application->MessageBox( "This operation can only be "
"performed by an administrator.", NULL, NULL);
}
//---------------------------------------------------------------------------

The second argument, also a string, is the caption that would display on the title bar of the dialog
box. You can also set it when creating the message box or you can build it from what would be
available at runtime. If you do not have a caption, you can set the value of this argument as NULL.
In that case the title bar would display Error. Therefore, to create a less boring message box,
provide the Caption argument. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Application->MessageBox("Make sure the music is playing.",
"CD PLayer Instructions", NULL);
}
//---------------------------------------------------------------------------

The third argument specifies the flags that would display on the dialog box: one or more buttons
and an optional picture. You can create a simple message box with OK as the only button. In that
case, set the third argument as MB_OK. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Application->MessageBox("Make sure the music is playing.",
"CD PLayer Instructions", MB_OK);
}
//---------------------------------------------------------------------------

To display more than one button, use a constant integer that represents a group of the available
buttons. Here are the constants and their buttons:

Constant Buttons
MB_OK

MB_OKCANCEL

MB_ABORTRETRYIGNORE

MB_YESNOCANCEL

MB_YESNO

MB_RETRYCANCEL

MB_HELP

For example, to create a message box that displays the Yes and No buttons, you could write:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Application->MessageBox("Do you hear any music now or any sound at all?",
"CD Player Instructions", MB_YESNO);
}
//---------------------------------------------------------------------------

If you provide the MB_HELP as the only button, the message box would display with an OK and a
Help buttons.

To enhance your dialog and accentuate your message, you can display an icon using one of the

3 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

Win32 defined integer constants. Although you can use any icon with any button, you should be
tactful and make sure that the appearance of the icon you use is in accordance with the message.
The values and icons are:

Value Icon Suited when


MB_ICONEXCLAMATION Warning the user of an action performed on
MB_ICONWARNING the application
MB_ICONINFORMATION
Informing the user of a non-critical situation
MB_ICONASTERISK
Asking a question that expects a Yes or No,
MB_ICONQUESTION
or a Yes, No, or Cancel answer
A critical situation or error has occurred.
MB_ICONSTOP
This icon is appropriate when informing the
MB_ICONERROR
user of a termination or deniability of an
MB_ICONHAND
action

The icons are used in conjunction with the buttons constant. To combine these two flags, use the
bitwise OR operator “|”. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Application->MessageBox("Do you hear any music now or any sound at all?",
"CD Player Instructions",
MB_YESNOCANCEL | MB_ICONQUESTION);
}
//---------------------------------------------------------------------------

When a message box is configured to display more than one button, the operating system is set to
decide which button is the default. The default button has a thick border that sets it apart from the
other button(s). If the user presses Enter, the message box would behave as if the user had clicked
the default button. Fortunately, if the message box has more than one button, you can decide what
button would be the default. To specify the default button, use one of the following constants:

If the message box has


more than one button,
Value
the default button
would be
MB_DEFBUTTON1 The first button
MB_DEFBUTTON2 The second button
MB_DEFBUTTON3 The third button
MB_DEFBUTTON4 The fourth button

To specify the default button, use the bitwise OR operator to combine the constant integer of the
desired default button with the button's constant and the icon. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Application->MessageBox("Do you hear any music now or any sound at all?",
"CD Player Instructions",
MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON2);
}
//---------------------------------------------------------------------------

Since the combination of these buttons is using the OR bitwise operator to construct the Flags
argument, it does not make a difference which constant appears first:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Application->MessageBox("Do you hear any music now or any sound at all?",
"CD Player Instructions",
MB_YESNOCANCEL | MB_DEFBUTTON3 | MB_ICONQUESTION);
}
//---------------------------------------------------------------------------

After reading the message displaying on the dialog box, the user would click one of the buttons and
the dialog would be closed. Each one of the buttons has a constant integer number that is assigned
and recognized by the compiler. You can use this number to find out what button the user had
clicked. This means that the MessageBox() function returns an integer value as in the following
table:

If the user The return value


Displayed Button(s)
clicked is
IDOK

IDOK

IDCANCEL

4 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

IDABORT

IDRETRY

IDIGNORE

IDYES

IDNO

IDCANCEL

IDYES

IDNO

IDRETRY

IDCANCEL

Therefore, you can use one of these integers to act depending on the button clicked:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if( Application->MessageBox(
"Do you hear any music now or any sound at all?",
"CD Player Instructions",
MB_YESNOCANCEL | MB_ICONQUESTION) == IDNO )
Panel1->Caption = "We will stop these tests now. "
"Let the machine rest!";
}
//---------------------------------------------------------------------------

Practical Learning: Using the MessageBox() Function


1. On the Component Palette, click Button and click on the form
2. Change the Caption of the new button to Simple &1 and its name to btnSimpleMsg
3. Double-click the Simple 1 button to access its click event
4. Press Tab and type:

Application->MessageBox("This operation can only be performed by an


administrator.", NULL, NULL);
5. To test the form, press F9
6. Click the Simple 1 button to view the message box. Notice that the message box has an OK
button and a caption of Error:

7. Click OK and close the form


8. Press F12 to display the form
9. Add another button to the form
10. Change its caption to Simple &2 and its name to btnSimple2
11. Double-click the Simple 2 button
12. Press Tab and type:

Application->MessageBox("Make sure the music is playing.", "CD PLayer


Instructions", MB_OK);
13. Test the form and return to Bcb
14. Add another button to the form
15. Change its caption to &Question and its name to btnQuestion
16. Double-click the Question button
17. Press Tab and type:

Application->MessageBox("Do you hear any music now or any sound at all?",


"CD Player Instructions",
MB_YESNOCANCEL | MB_ICONQUESTION);

18. Test the form:

5 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

19. Return to Bcb


20. Add another button to the form
21. Change its caption to &Default and its name to btnDefault
22. Double-click the Default button and implement its event as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnDefaultClick(TObject *Sender)
{
Application->MessageBox(
"The file you are trying to copy is being "
"used by someone else.\n"
"Would you like to try later? If you click\n"
"Yes: You will be reminded when the file is ready.\n"
"No: Copy the file anyway. You will get only the source file\n"
"Cancel: Cancel the operation.", "Copying Files",
MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON2);
}
//---------------------------------------------------------------------------

23. Test the form:

24. Return to Bcb

VCL Custom Message Boxes

The Message Box as a Dialog


The MessageDlg() function is Borland’s enhanced message box and it provides a good alternative
to the Win32’s MessageBox() function:

The syntax of the MessageDlg() function is:

int __fastcall MessageDlg(const AnsiString Message,


TMsgDlgType IconType,
TMsgDlgButtons Buttons,
int HelpContext);

The first argument, Message, is the message addressed to the user. It can be a simple static
sentence, a paragraph or any combination of strings. The IconType is an icon used to enhance the
dialog box. The icon is set using a constant integer as follows:

Value Icon

mtWarning

mtError

mtInformation

mtConfirmation

mtCustom None

6 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

The Buttons argument is used to specify the type(s) of button(s) to display on the dialog box. The
buttons are defined using the TMsgDlgButtons set as follows:

Value Button Value Button


mbYes mbRetry

mbNo mbIgnore

mbOK mbAll
mbCancel mbNoToAll
mbAbort mbYesToAll
mbHelp

The last argument is used if there is a help file available, in which case you would specify the
particular index related to this message box. This message box uses the name of the project as its
caption.

Practical Learning: Using the MessageDlg() Function


1. Add a button to the form
2. Change its caption to Msg Di&alog 1 and its name to btnMsgDialog1
3. Double-click the Msg Dlg 1 button
4. Press Tab and type:

MessageDlg("All songs on the CD have been copied. Now it will be ejected.",


mtInformation, TMsgDlgButtons() << mbOK, 0);

5. Test the form


6. Add a button to the form
7. Change its caption to Msg Dia&log 2 and its name to btnMsgDlg2
8. Double-click the Msg Dialog2 button and implement it as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnMsgDlg2Click(TObject *Sender)
{
MessageDlg("The file " + AnsiString("\"") +
edtMessage->Text + AnsiString("\"") +
" that you are trying to upload "
"already exists on the server.\n"
"If you continue, you will replace the recent versions "
"of the files on the server.\n"
"Would you like to upload anyway?",
mtConfirmation, TMsgDlgButtons() << mbNoToAll
<< mbNo << mbYes
<< mbYesToAll, 0);
}
//---------------------------------------------------------------------------

9. To test the form, press F9


10. In the Message edit box, type canonderby.asp
11. Click the Msg Dialog 2 button:

12. Return to Bcb

The Message Box and its Position


The MessageDlgPos() function provides extra possibilities to the programmer. It behaves exactly
like the MessageDlg() function. To create a message box based on this function, use the syntax:

int __fastcall MessageDlgPos(const AnsiString Msg, TMsgDlgType DlgType,


TMsgDlgButtons Buttons, int HelpCtx, int X, int Y);

Besides the same arguments as the MessageDlg() function, The MessageDlgPos() function
allows you to specify the coordinates used to display the dialog box. The X argument is an integer
value that specifies the distance between the left border of the screen and the left border of the

7 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

dialog box. The Y argument represents the height from the top border of the screen to the top
border of the dialog box. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
MessageDlgPos("The right side of the main form displays "
"a \"Read-Only\" list of currently registered students.\n"
"This only includes students with good records.",
mtInformation,
TMsgDlgButtons() << mbRetry
<< mbIgnore, 0, 20, 120);
}
//---------------------------------------------------------------------------

Message Created From a Dialog


If you have a prototype message box that you are planning to use over and over again in your
application, you create it at once, implement it, then use in different locations in your application.
Such a common message box is created using the CreateMessageDialog() function. The
CreateMessageDialog() function does not allow you to create a new message box. It provides a
technique of creating a central dialog box that combines the arguments and flags of the other
message boxes. The syntax of the CreateMessageDialog() function is:

Forms::TForm* __fastcall CreateMessageDialog(const AnsiString Msg,


TMsgDlgType IconType,
TMsgDlgButtons ButtonType);

This function takes three arguments similar to those of the MessageDlg() function. You construct
it by specifying the string message, the icon type, and the button type. To create this dialog box,
assign its construction to a dynamic form. To do this, you could create a local form in a function or
event, but since a local dynamic control is accessible only in the event or function in which it is
created, this would deceive the purpose of using the CreateMessageDialog() function. Therefore,
declare an instance of the TForm class in the private or public sections of the unit or form that
would use the message box:

//---------------------------------------------------------------------------
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
TButton *Button2;
TPanel *Panel1;
void __fastcall Button1Click(TObject *Sender);
void __fastcall Button2Click(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
void __fastcall Panel1Click(TObject *Sender);

private: // User declarations


TForm* Mine;

public: // User declarations


__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

Next, use the new operator to specify the owner of the form:

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Mine = new TForm(this);
}
//---------------------------------------------------------------------------

To create the custom message box, assign the return value of the CreateMessageDialog()
function by creating it. The message box can be as simple as a single string, an icon, and a button:

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Mine = new TForm(this);

Mine = CreateMessageDialog("Custom Dialog Box", mtWarning,

8 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

TMsgDlgButtons() << mbYes);


}
//---------------------------------------------------------------------------

The message could also comport any of the available icons combined with any common buttons:

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Mine = new TForm(this);
Mine = CreateMessageDialog("Is this the best song or what?",
mtInformation,
TMsgDlgButtons() << mbYes << mbAbort
<< mbCancel << mbNo);
}
//---------------------------------------------------------------------------

With the message box created, you can call it from any section or control that needs it in your
application:

#include <vcl.h>
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Mine = new TForm(this);
Mine = CreateMessageDialog("Is this the best song or what?",
mtInformation,
TMsgDlgButtons() << mbYes << mbAbort
<< mbCancel << mbNo);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Mine->ShowModal();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Mine->ShowModal();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Panel1Click(TObject *Sender)
{
Mine->ShowModal();
}
//---------------------------------------------------------------------------

The Input Dialog Box


The InputBox() function allows you to display a message box that would request a piece of
information from the user. The message box is equipped with an edit box and two buttons. The edit
box accepts a string from the user. The user can type anything but it is up to you to use the
content of that edit box as your program needs it. When the user clicks OK, the Input Box returns
the content of its edit box. If the user clicks Cancel or presses Esc, the content of its edit box is
dismissed.

The syntax of the InputBox() function is

AnsiString __fastcall InputBox(const AnsiString Caption,


const AnsiString Prompt, const AnsiString Default);

The Caption argument specifies the string that would display on the title bar of the dialog box. The
Prompt is a sentence that would display to the user as to what to type in the provided edit box. The
Default argument is a suggested value you can display in the edit box to guide the user as the type
of value expected. If you do not want to specify a default value, you can set its string value to
empty. Here is example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
InputBox("Distance and Measurement",
"Enter the distance in kilometer:", "");

9 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

}
//---------------------------------------------------------------------------

If you specify the Default argument and the user clicks OK without changing the content of the edit
box, the compiler would consider the default value as valid. After using the dialog box, the user
would click OK, press Enter, click Cancel, or press Esc. If the user clicks OK or presses Enter, the
function returns the value that the user would have typed in the edit box. This allows you to write
a conditional statement that would consider the new value returned by clicking OK on the
InputBox dialog:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Edit1->Text = InputBox("Distance and Measurement",
"Enter the distance in kilometer:", "");
}
//---------------------------------------------------------------------------

If the user clicks Cancel or presses Esc, whatever the edit box was displaying would be ignored. But
the function would still return the default value. If the returned value is intended for
mathematical, date, or time calculations, you should convert it accordingly.

Practical Learning: Using the InputBox Dialog

1. Add a button to the form


2. Double-click it. Press Tab and type

InputBox("Student Registration", "Type the Student's Gender", "");


3. Press F9 to test the form. Click the new button. Notice that the content of its edit box is empty
4. Close the Input Box and the form

The InputQuery Request


Like the InputBox() function, the InputQuery() function is used to display a prompting dialog
box to the user. The syntax of this function is:

extern PACKAGE bool __fastcall InputQuery(constAnsiString ACaption,


const AnsiString APrompt,
AnsiString &Value);

This takes three strings. The Caption parameter is a string that displays on the title bar of the
dialog box. The Prompt parameter is the sentence that indicates to the user what to type in the
edit box. Like the InputBox() function, the Value parameter provides a default and sample value
to the user. Like the InputBox() function, the user can type a new value. Here is an example of
using the InputQuery() function:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AnsiString Value;

InputQuery("Exiting Application",
"Are you sure you want to exist (y=Yes/n=No)?",
Value);
}
//---------------------------------------------------------------------------

Unlike the InputBox() function that returns a string, the InputQuery() function returns two
values. By its declaration, this function returns a Boolean value of true or false. If the user clicks
OK or presses Enter after using the dialog box, the function returns true. If the user presses Esc or
clicks Cancel, the function returns false.

If the user clicks OK (or presses Enter), like the InputBox() function, whether the user had
changed the value of the edit box or not, the content of the edit box, provided as the Value
argument, would be returned. Because Value is passed by reference, the function can return two
values. Unlike the InputBox() function, if the user clicks Cancel (or presses Esc) after dealing
with the dialog box, the value of the Value argument would be ignored.

You can validate the returned value of Value by writing a conditional statement that examines
whether the user had clicked OK or Cancel. In the following example, when the user clicks a button
on the form, the compiler finds out if the user had clicked OK; in which case it would display the
returned value of the Value argument in an Edit control of the form:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AnsiString Answer;

if( InputQuery("Exiting Application",


"Are you sure you want to exist (Y=Yes/Y=No)?",
Answer) == True )

10 de 11 10/04/2015 16:23
Borland C++ Builder: Message Boxes http://www.functionx.com/bcb/topics/msgbox.htm

Edit1->Text = Answer;
}
//---------------------------------------------------------------------------

Home Copyright © 2004-2010 FunctionX, Inc.

11 de 11 10/04/2015 16:23