Está en la página 1de 23

Darwin Durand Morillo

ALGORITMOS II

MessageBox

Overview Descripción general

A message box is a relatively small dialog box used to display a message and provide one or
more buttons. Un cuadro de mensaje es un cuadro de diálogo relativamente pequeñas que se
utilizan para mostrar un mensaje y la prestación de uno o más botones. Here is an example of
a message box: Aquí hay un ejemplo de un cuadro de mensaje:

A message box is used to provide information to the user or to request a decision (from the
user). Un cuadro de mensaje se utiliza para proporcionar al usuario información o para
solicitar una decisión (del usuario). By clicking one of the buttons, the user makes a decision
and the program continues. Al hacer clic en uno de los botones, el usuario toma una decisión
y el programa continúa.

Message boxes are created from built-in functions from the VCL and the Win32 library. Los
cuadros de mensaje son creados a partir de las funciones integradas de la VCL y la biblioteca
Win32. The necessary functions shipped with the compiler. Las funciones necesarias se incluye
con el compilador.

Practical Learning: Preparing the Message Boxes Application De aprendizaje


práctico: preparación de la solicitud cuadros de mensaje

1. Create a new project with its starting form Crear un nuevo proyecto con su forma de
partida
2. Change its Caption to Message Boxes Configuration Cambiar su título a cuadros de
mensaje de configuración
3. From the Standard tab of the Component Palette, click the Edit control and click on the
form En la ficha estándar de la paleta de componentes, haga clic en el control de edición y
haga clic en el formulario de
4. Change the name of the edit control to edtMessage and delete the contents of its Text
field. Cambie el nombre del control de edición de edtMessage y borrar el contenido de su
campo de texto.

Message Showing Listado de mensajes

The ShowMessage() function provides the most fundamental of Borland's message boxes. El
ShowMessage () proporciona la función más fundamental de los cuadros de mensaje de
Borland. This function takes one string argument and does not return any value. Esta función
tiene un argumento de cadena y no devuelve ningún valor. It is used to display a message to
the user who acknowledges it by clicking the OK button. Se utiliza para mostrar un mensaje al
usuario que reconoce que haciendo clic en el botón Aceptar. The syntax of the

1
Darwin Durand Morillo
ALGORITMOS II

ShowMessage() function is: La sintaxis de la ShowMessage () es:

void __fastcall ShowMessage(const AnsiString Message); void __fastcall ShowMessage (const


AnsiString Message);

A message box created with the ShowMessage() function uses the name of the project as its
caption. Un cuadro de mensaje creado con el ShowMessage () función utiliza el nombre del
proyecto como su título. The message to display is a string that can be provided by the
developer. El mensaje que se mostrará es una cadena que puede ser proporcionado por el
desarrollador. Here is an example: Aquí está un ejemplo:

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

The string can also derive from another control such as the contents of an edit box, a memo, or
any text control. La cadena también puede derivar de otro control, como el contenido de un
cuadro de edición, una nota, o cualquier control de texto. Here is an example: Aquí está un
ejemplo:

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

The string can also be a combination of other strings: La cadena también puede ser una
combinación de otras cadenas:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
ShowMessage("The name " + AnsiString("\"") + ShowMessage ( "El nombre" +
AnsiString ( "\" ") +
edtMessage->Text + AnsiString("\"") + " is not in our records."); edtMessage-> Text +
AnsiString ( "\" ") +" no está en nuestros registros. ");
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

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'. Al igual que

2
Darwin Durand Morillo
ALGORITMOS II

con otros cuadros de mensaje que vamos a estudiar aquí, para mostrar el mensaje en varias
líneas de texto, puede separar líneas usando la C / C + + nueva línea constante representada
por '\ n'. The VCL provides another alternative. La VCL ofrece otra alternativa. To separate lines
of text, you can use the sLineBreak constant. Para separar líneas de texto, puede utilizar el
sLineBreak constante. Here is an example: Aquí está un ejemplo:

//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1::
Button1Click (TObject * Sender)
{(
AnsiString strMessage = "Your record has been registered"; StrMessage
AnsiString = "Su registro ha sido registrado";
AnsiString strCountry = "Country Name: Australia"; AnsiString strPaís =
"Nombre del País: Australia";
AnsiString strCity = "City to visit: Melbourne"; StrCity AnsiString =
"Ciudad a visitar: Melbourne";
AnsiString strFinal = "Have a nice strip."; AnsiString strFinal = "cuenta
con una banda de Niza.";

ShowMessage(strMessage + sLineBreak + strCountry + sLineBreak +


ShowMessage (strMessage sLineBreak + + + strPaís sLineBreak +
strCity + sLineBreak + strFinal); strCity + sLineBreak
+ strFinal);
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------

Practical Learning: Using the ShowMessage() Function Aprendizaje Práctico: Uso de


la ShowMessage () Función

1. From the Standard tab of the Component Palette, click Button and click on the form En la
ficha estándar de la paleta de componentes, haga clic en el botón y haga clic en el
formulario de
2. Change the caption of the new button to Show &Msg and change its name to btnShowMsg
Cambiar el título del botón de nuevo para mostrar y mensaje y cambiar su nombre a
btnShowMsg
3. Double-click the Show Msg button to access its Click event Haga doble clic en el botón
Mostrar mensaje para acceder a su evento Click
4. Press Tab and implement it as follows: Presione la tecla Tab y aplicar de la siguiente
manera:

3
Darwin Durand Morillo
ALGORITMOS II

//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
void __fastcall TForm1::btnShowMsgClick(TObject *Sender) void __fastcall
TForm1:: btnShowMsgClick (TObject * Sender)
{(
ShowMessage("Please fill out your Time Sheet before leaving.");
ShowMessage ( "Por favor, rellene su hoja de horas antes de salir.");
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------

5. To test the program, press F9 Para probar el programa, pulse F9


6. Click the Show Msg button: Haga clic en el botón Mostrar Mensaje:

7. Click OK and close the form Haga clic en Aceptar y cierre el formulario
8. To save the project, on the main menu, click File -> Save All Para guardar el proyecto, en
el menú principal, haga clic en Archivo -> Guardar todo
9. Locate the folder where the exercises are installed Busque la carpeta donde están
instalados los ejercicios
10. Click the Create New folder button. Haga clic en el botón Crear nueva carpeta. Type
Message Boxes and press Enter twice to display the new folder in the Save In combo box
Tipo de cuadros de mensaje y pulse Enter dos veces para mostrar la nueva carpeta en el
cuadro Guardar en combo
11. Click Save to save the Unit Haga clic en Guardar para guardar la Unidad de
12. Type Messages to replace the name of the project and press Enter Tipo de mensajes a
sustituir el nombre del proyecto y pulse Enter
13. To display the message on more than one line, change the event as follows: Para mostrar
el mensaje en más de una línea, cambiar el evento como sigue:
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
void __fastcall TForm1::btnShowMsgClick(TObject *Sender) void __fastcall
TForm1:: btnShowMsgClick (TObject * Sender)
{(
ShowMessage("Please fill out your Time Sheet before leaving.\n"
ShowMessage ( "Por favor, rellene su hoja de horas antes de salir. \ N"
"Make sure you sign and send it to Human Resources.");
"Asegúrese de firmar y enviar a Recursos Humanos.");
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------

14. Test the form to verify the new caption of the message box: Pruebe el formulario para
verificar el nuevo título del cuadro de mensaje:

4
Darwin Durand Morillo
ALGORITMOS II

15. And return to Bcb Y volver a Bcb

The Win32 Message Box El cuadro de mensaje de Win32

The MessageBox() function is derived from Win32. La función MessageBox () se deriva de


Win32. Its syntax is: Su sintaxis es:

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

The MessageBox() function takes three arguments. La función MessageBox () toma tres
argumentos. The first argument, Message, is a null-terminated string representing the message
that the user would read. El primer argumento, mensaje, es una cadena terminada en nulo que
representa el mensaje de que el usuario pueda leer. The Message string could be a static
sentence. La cadena de mensaje podría ser una sentencia de estática. It could be constructed
from another control. Podría ser construido a partir de otro control. Or it could be a combination
of different strings appended using C/C++ string functions and operations. O podría ser una
combinación de diferentes cadenas anexo en C / C + + funciones de cadena y de las
operaciones.

You can create a simple message box similar to one implemented using the ShowMessage()
function to display a simple message with an OK button. Usted puede crear un cuadro de
mensaje simple similar a uno implementado utilizando el ShowMessage () para mostrar un
mensaje simple con un botón Aceptar. In this case, you would provide only the Message
argument. En este caso, debe proporcionar sólo el argumento de mensajes. Set the other two
arguments as NULL. Establecer los otros dos argumentos como NULL. Here is an example: Aquí
está un ejemplo:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Application->MessageBox( "This operation can only be " Application-> MessageBox ( "Esta
operación sólo puede ser"
"performed by an administrator.", NULL, NULL); "realizado por un administrador.", NULL, NULL);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

The second argument, also a string, is the caption that would display on the title bar of the
dialog box. El segundo argumento, también una cadena, es el título que aparece en la barra de
título del cuadro de diálogo. You can also set it when creating the message box or you can build
it from what would be available at runtime. También puede establecer que al crear el cuadro de
mensaje o usted puede construir desde lo que estaría disponible en tiempo de ejecución. If you
do not have a caption, you can set the value of this argument as NULL. Si usted no tiene un

5
Darwin Durand Morillo
ALGORITMOS II

título, puede establecer el valor de este argumento como NULL. In that case the title bar would
display Error. En ese caso, la barra de título mostrará un error. Therefore, to create a less
boring message box, provide the Caption argument. Por lo tanto, para crear un cuadro de
mensaje menos aburrido, proporcionar el argumento de Leyenda. Here is an example: Aquí
está un ejemplo:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Application->MessageBox("Make sure the music is playing.", Application-> MessageBox
( "Asegúrese de que la música se reproduce."
"CD PLayer Instructions", NULL); "Reproductor de CD de
instrucciones", NULL);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

The third argument specifies the flags that would display on the dialog box: one or more
buttons and an optional picture. El tercer argumento especifica los indicadores que se muestran
en el cuadro de diálogo: uno o más botones y una imagen opcional. You can create a simple
message box with OK as the only button. Usted puede crear un cuadro de mensaje simple con
el botón Aceptar como solamente. In that case, set the third argument as MB_OK. En ese caso,
establezca el tercer argumento como MB_OK. Here is an example: Aquí está un ejemplo:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Application->MessageBox("Make sure the music is playing.", Application-> MessageBox
( "Asegúrese de que la música se reproduce."
"CD PLayer Instructions", MB_OK); "Reproductor de CD de
instrucciones", MB_OK);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

To display more than one button, use a constant integer that represents a group of the
available buttons. Para mostrar más de un botón, utilice una constante entera que representa a
un grupo de los botones disponibles. Here are the constants and their buttons: Éstos son las
constantes y sus botones:

Constant Constante Buttons Botones

MB_OK MB_OK

MB_OKCANCEL
MB_OKCANCEL
MB_ABORTRETRYIGNORE
MB_ABORTRETRYIGNORE
MB_YESNOCANCEL
MB_YESNOCANCEL

6
Darwin Durand Morillo
ALGORITMOS II

MB_YESNO MB_YESNO

MB_RETRYCANCEL
MB_RETRYCANCEL

MB_HELP MB_HELP

For example, to create a message box that displays the Yes and No buttons, you could write:
Por ejemplo, para crear un cuadro de mensaje que muestra los botones Sí y No, usted podría
escribir:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Application->MessageBox("Do you hear any music now or any sound at all?",
Application-> MessageBox ( "¿Me oyes ahora cualquier tipo de música o cualquier sonido en
absoluto?",
"CD Player Instructions", MB_YESNO); "Reproductor de CD
de instrucciones", MB_YESNO);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

If you provide the MB_HELP as the only button, the message box would display with an OK
and a Help buttons. Si usted proporciona el MB_HELP como el único botón, el cuadro de
mensaje se muestra con un clic en Aceptar y un botón de Ayuda.

To enhance your dialog and accentuate your message, you can display an icon using one of the
Win32 defined integer constants. Para mejorar su diálogo y acentuar su mensaje, puede
mostrar un icono con una de las constantes de Win32 se define entero. 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. Aunque puede utilizar cualquier icono con cualquier
botón, usted debe ser discreto y asegurarse de que la aparición del icono que se utiliza es de
acuerdo con el mensaje. The values and icons are: Los valores y los iconos son los siguientes:

Icon
Value Valor Suited when Adecuado cuando
Icono
MB_ICONEXCLAMATION
Warning the user of an action performed on
MB_ICONEXCLAMATION
the application Advirtiendo al usuario de una
MB_ICONWARNING
acción realizada en la aplicación de
MB_ICONWARNING
MB_ICONINFORMATION
Informing the user of a non-critical situation
MB_ICONINFORMATION
Informar al usuario de una situación no
MB_ICONASTERISK
crítica
MB_ICONASTERISK
Asking a question that expects a Yes or No,
MB_ICONQUESTION or a Yes, No, or Cancel answer Hacer una
MB_ICONQUESTION pregunta que espera un Sí o No, o responder
a una Sí, No o Cancelar
MB_ICONSTOP A critical situation or error has occurred. Una
MB_ICONSTOP situación crítica o error ha ocurrido. This icon
MB_ICONERROR is appropriate when informing the user of a
MB_ICONERROR termination or deniability of an action Este

7
Darwin Durand Morillo
ALGORITMOS II

icono se utiliza cuando la información para el


MB_ICONHAND
usuario de una resolución o negación de una
MB_ICONHAND
acción

The icons are used in conjunction with the buttons constant. Los iconos se utilizan en
combinación con los botones constante. To combine these two flags, use the bitwise OR
operator “|”. Para combinar estas dos banderas, utilice el operador OR bit a bit "|". Here is an
example: Aquí está un ejemplo:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Application->MessageBox("Do you hear any music now or any sound at all?",
Application-> MessageBox ( "¿Me oyes ahora cualquier tipo de música o cualquier sonido en
absoluto?",
"CD Player Instructions", "Reproductor de CD de
instrucciones",
MB_YESNOCANCEL | MB_ICONQUESTION); 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. Cuando un cuadro de mensaje está configurado para
mostrar más de un botón, el sistema operativo está configurado para decidir qué botón es el
predeterminado. The default button has a thick border that sets it apart from the other
button(s). El botón predeterminado tiene un borde grueso que lo distingue de los otros dos
botones (s). If the user presses Enter, the message box would behave as if the user had clicked
the default button. Si el usuario pulsa Intro, el cuadro de mensaje que se comportan como si el
usuario ha hecho clic en el botón predeterminado. Fortunately, if the message box has more
than one button, you can decide what button would be the default. Afortunadamente, si el
cuadro de mensaje tiene más de un botón, usted puede decidir lo que sería el botón
predeterminado. To specify the default button, use one of the following constants: Para
especificar el botón por defecto, utilice una de las siguientes constantes:

If the message box has


more than one button,
the default button
Value Valor would be Si el cuadro
de mensaje tiene más
de un botón, el botón
por defecto sería
MB_DEFBUTTON1 The first button El primer
MB_DEFBUTTON1 botón
MB_DEFBUTTON2 The second button El
MB_DEFBUTTON2 segundo botón
MB_DEFBUTTON3 The third button El tercer
MB_DEFBUTTON3 botón
MB_DEFBUTTON4 The fourth button El
MB_DEFBUTTON4 cuarto botón

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. Para especificar el botón por
defecto, utilice el operador OR bit a bit para combinar la constante entera del botón

8
Darwin Durand Morillo
ALGORITMOS II

predeterminado deseado con el botón de la constante y el icono. Here is an example: Aquí está
un ejemplo:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Application->MessageBox("Do you hear any music now or any sound at all?",
Application-> MessageBox ( "¿Me oyes ahora cualquier tipo de música o cualquier sonido en
absoluto?",
"CD Player Instructions", "Reproductor de CD de
instrucciones",
MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON2); 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: Dado que la combinación
de estos botones es usando el operador OR bit a bit para construir el argumento de Banderas,
que no hace una diferencia constante que aparece en primer lugar:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Application->MessageBox("Do you hear any music now or any sound at all?",
Application-> MessageBox ( "¿Me oyes ahora cualquier tipo de música o cualquier sonido en
absoluto?",
"CD Player Instructions", "Reproductor de CD de
instrucciones",
MB_YESNOCANCEL | MB_DEFBUTTON3 | MB_ICONQUESTION); 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. Después de leer el mensaje que muestra en el cuadro de
diálogo, el usuario haga clic en uno de los botones y el cuadro de diálogo se cerrará. Each one
of the buttons has a constant integer number that is assigned and recognized by the compiler.
Cada uno de los botones tiene un número entero constante que se le asigna y reconocido por el
compilador. You can use this number to find out what button the user had clicked. Usted puede
usar este número para averiguar qué botón el usuario ha hecho clic. This means that the
MessageBox() function returns an integer value as in the following table: Esto significa que la
función MessageBox () devuelve un valor entero como en el siguiente cuadro:

If the user
The return value
Displayed Button(s) Botón de clicked Si el
is El valor de
muestra (s) usuario
retorno es
hace clic en

9
Darwin Durand Morillo
ALGORITMOS II

IDOK IDOK

IDOK IDOK

IDCANCEL
IDCANCEL
IDABORT
IDABORT
IDRETRY
IDRETRY
IDIGNORE
IDIGNORE

IDYES IDYES

IDNO IDNO

IDCANCEL
IDCANCEL

IDYES IDYES

IDNO IDNO

IDRETRY
IDRETRY
IDCANCEL
IDCANCEL

Therefore, you can use one of these integers to act depending on the button clicked: Por lo
tanto, puede utilizar uno de estos números enteros para actuar en función de hacer clic en el
botón:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
if( Application->MessageBox( if (Application-> MessageBox (
"Do you hear any music now or any sound at all?", "¿Me oyes ahora
cualquier tipo de música o cualquier sonido en absoluto?",
"CD Player Instructions", "Reproductor de CD de instrucciones",
MB_YESNOCANCEL | MB_ICONQUESTION) == IDNO )
MB_YESNOCANCEL | MB_ICONQUESTION) == IDNO)
Panel1->Caption = "We will stop these tests now. " Button1-> Caption =
"Vamos a poner fin a estas pruebas ahora".
"Let the machine rest!"; "Que el resto de máquinas";
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

Practical Learning: Using the MessageBox() Function De aprendizaje práctico: Uso

10
Darwin Durand Morillo
ALGORITMOS II

de la función MessageBox ()

1. On the Component Palette, click Button and click on the form En la paleta de
componentes, haga clic en el botón y haga clic en el formulario de
2. Change the Caption of the new button to Simple &1 and its name to btnSimpleMsg
Cambiar el título del nuevo botón a Simple y 1 y su nombre a btnSimpleMsg
3. Double-click the Simple 1 button to access its click event Haga doble clic en el simple 1
botón para acceder a su evento, haga clic en
4. Press Tab and type: Presione la tecla Tab y escriba:

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


administrator.", NULL, NULL); Application-> MessageBox ( "Esta operación sólo
puede ser realizado por un administrador.", NULL, NULL);
5. To test the form, press F9 Para probar el formulario, presionar la tecla F9
6. Click the Simple 1 button to view the message box. Simple 1 Haga clic en el botón para
ver el cuadro de mensaje. Notice that the message box has an OK button and a caption of
Error: Observe que el cuadro de mensaje que tiene un botón Aceptar y una leyenda de
error:

7. Click OK and close the form Haga clic en Aceptar y cierre el formulario
8. Press F12 to display the form Pulse F12 para mostrar el formulario
9. Add another button to the form Agregue otro botón a la forma
10. Change its caption to Simple &2 and its name to btnSimple2 Cambiar su título a Simple y
2, y su nombre a btnSimple2
11. Double-click the Simple 2 button Haga doble clic en el botón Simple 2
12. Press Tab and type: Presione la tecla Tab y escriba:

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


Instructions", MB_OK); Application-> MessageBox ( "Asegúrese de que la música
se reproduce.", "Reproductor de CD de instrucciones", MB_OK);
13. Test the form and return to Bcb Prueba de la forma y volver a Bcb
14. Add another button to the form Agregue otro botón a la forma
15. Change its caption to &Question and its name to btnQuestion Cambiar su título y la
pregunta y su nombre a btnQuestion
16. Double-click the Question button Haga doble clic en el botón de preguntas
17. Press Tab and type: Presione la tecla Tab y escriba:
Application->MessageBox("Do you hear any music now or any sound at all?",
Application-> MessageBox ( "¿Me oyes ahora cualquier tipo de música o cualquier
sonido en absoluto?",

11
Darwin Durand Morillo
ALGORITMOS II

"CD Player Instructions", "Reproductor de CD de


instrucciones",
MB_YESNOCANCEL | MB_ICONQUESTION);
MB_YESNOCANCEL | MB_ICONQUESTION);

18. Test the form: Prueba de la siguiente forma:

19. Return to Bcb Volver a Bcb


20. Add another button to the form Agregue otro botón a la forma
21. Change its caption to &Default and its name to btnDefault Cambiar su título y por defecto
y su nombre a btnDefault
22. Double-click the Default button and implement its event as follows: Haga doble clic en el
botón predeterminado y aplicar su evento como sigue:
//--------------------------------------------------------------------------- //-------------
----------------------------------- ---------------------------
void __fastcall TForm1::btnDefaultClick(TObject *Sender) void __fastcall TForm1::
btnDefaultClick (TObject * Sender)
{(
Application->MessageBox( Application-> MessageBox (
"The file you are trying to copy is being " "El archivo que
está intentando copiar está siendo"
"used by someone else.\n" "utilizado por otra persona. \
n"
"Would you like to try later? If you click\n" "¿Te gustaría
probar más tarde? Si hace clic en \ n"
"Yes: You will be reminded when the file is ready.\n"
"Sí: Se le recuerda a cuando el archivo esté listo. \ N"
"No: Copy the file anyway. You will get only the source file\n"
"No: Copia el archivo de todos modos. Usted recibirá sólo la fuente de archivo \ n"
"Cancel: Cancel the operation.", "Copying Files",
"Cancelar: Cancelar la operación.", "Copia de archivos",
MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON2);
MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON2);
})
//--------------------------------------------------------------------------- //-------------
----------------------------------- ---------------------------

23. Test the form: Prueba de la siguiente forma:

12
Darwin Durand Morillo
ALGORITMOS II

24. Return to Bcb Volver a Bcb

VCL Custom Message Boxes VCL Mensaje personalizado Cajas

The Message Box as a Dialog El cuadro de mensaje como un cuadro de diálogo

The MessageDlg() function is Borland's enhanced message box and it provides a good
alternative to the Win32's MessageBox() function: El MessageDlg () es mejor cuadro de
mensaje de Borland y proporciona una buena alternativa a la de mensaje de Win32 () Función:

The syntax of the MessageDlg() function is: La sintaxis de la MessageDlg () es:

int __fastcall MessageDlg(const AnsiString Message, int __fastcall MessageDlg (const AnsiString
Mensaje,
TMsgDlgType IconType, TMsgDlgType IconType,
TMsgDlgButtons Buttons, TMsgDlgButtons Botones,
int HelpContext); HelpContext int);

The first argument, Message, is the message addressed to the user. El primer argumento,
mensaje, es el mensaje dirigido al usuario. It can be a simple static sentence, a paragraph or
any combination of strings. Puede ser una frase simple estática, un párrafo o una combinación
de cadenas. The IconType is an icon used to enhance the dialog box. El IconType es un icono
que se utiliza para mejorar el cuadro de diálogo. The icon is set using a constant integer as
follows: El icono se establece utilizando una constante entera de la siguiente manera:

Icon
Value
Icon
Valor
o
mtWarni
ng
mtWarni
ng
mtError
mtError

13
Darwin Durand Morillo
ALGORITMOS II

mtInfor
mation
mtInfor
mation
mtConfir
mation
mtConfir
mation
mtCusto Non
m e
mtCusto Ning
m uno

The Buttons argument is used to specify the type(s) of button(s) to display on the dialog box.
El argumento de los botones se utiliza para especificar el tipo (s) de botón (s) para mostrar en
el cuadro de diálogo. The buttons are defined using the TMsgDlgButtons set as follows: Los
botones se definen mediante el TMsgDlgButtons establecido como sigue:

Value Button Button


Value Valor
Valor Botón Botón
mbYes mbRetry
mbYes mbRetry
mbNo mbIgnore
mbNo mbIgnore
mbOK mbAll
mbOK mbAll
mbCancel mbNoToAll
mbCancel mbNoToAll
mbAbort mbYesToAll
mbAbort mbYesToAll
mbHelp
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. El último argumento se utiliza si hay un archivo de
ayuda disponibles, en cuyo caso debe especificar el índice en particular en relación con este
cuadro de mensaje. This message box uses the name of the project as its caption. Este cuadro
de mensaje utiliza el nombre del proyecto como su título.

Practical Learning: Using the MessageDlg() Function Aprendizaje Práctico: Uso de la


MessageDlg () Función

1. Add a button to the form Agregar un botón a la forma


2. Change its caption to Msg Di&alog 1 and its name to btnMsgDialog1 Cambiar su título a
Mensaje Di & 1 Alog y su nombre a btnMsgDialog1
3. Double-click the Msg Dlg 1 button Haga doble clic en el botón Dlg MSG 1
4. Press Tab and type: Presione la tecla Tab y escriba:
MessageDlg("All songs on the CD have been copied. Now it will be ejected.",
MessageDlg ( "Todas las canciones en el CD se han copiado. Ahora será
expulsado."

14
Darwin Durand Morillo
ALGORITMOS II

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


mtInformation, TMsgDlgButtons () <<mbOK, 0);
5. Test the form Pruebe el formulario
6. Add a button to the form Agregar un botón a la forma
7. Change its caption to Msg Dia&log 2 and its name to btnMsgDlg2 Cambiar su título
Mensaje Dia & log 2 y su nombre a btnMsgDlg2
8. Double-click the Msg Dialog2 button and implement it as follows: Haga doble clic en el
botón Dialog2 mensaje y ponerlo en práctica de la siguiente manera:
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
void __fastcall TForm1::btnMsgDlg2Click(TObject *Sender) void __fastcall
TForm1:: btnMsgDlg2Click (TObject * Sender)
{(
MessageDlg("The file " + AnsiString("\"") + MessageDlg ( "El archivo" +
AnsiString ( "\" ") +
edtMessage->Text + AnsiString("\"") + edtMessage->
Text + AnsiString ( "\" ") +
" that you are trying to upload " "Que está tratando
de subir"
"already exists on the server.\n" "ya existe en el
servidor. \ n"
"If you continue, you will replace the recent versions "
"Si continúa, que reemplazará las versiones recientes"
"of the files on the server.\n" "de los archivos en el
servidor. \ n"
"Would you like to upload anyway?", "¿Te gustaría
subir de todos modos?",
mtConfirmation, TMsgDlgButtons() << mbNoToAll ,
mtConfirmation TMsgDlgButtons () <<mbNoToAll
<< mbNo << mbYes <<MbNo <<mbYes
<< mbYesToAll, 0); <<MbYesToAll, 0);
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
9. To test the form, press F9 Para probar el formulario, presionar la tecla F9
10. In the Message edit box, type canonderby.asp En el cuadro de edición de mensajes,
canonderby.asp tipo de
11. Click the Msg Dialog 2 button: Haga clic en el cuadro de diálogo Mensaje de 2 botones:

12. Return to Bcb Volver a Bcb

15
Darwin Durand Morillo
ALGORITMOS II

The Message Box and its Position El cuadro de mensaje y de su posición

The MessageDlgPos() function provides extra possibilities to the programmer. El


MessageDlgPos () función ofrece posibilidades adicionales para el programador. It behaves
exactly like the MessageDlg() function. Se comporta exactamente como el MessageDlg () la
función. To create a message box based on this function, use the syntax: Para crear un cuadro
de mensaje sobre la base de esta función, utilice la sintaxis:

int __fastcall MessageDlgPos(const AnsiString Msg, TMsgDlgType DlgType, int __fastcall


MessageDlgPos (const AnsiString Msg, TMsgDlgType DlgType,
TMsgDlgButtons Buttons, int HelpCtx, int X, int Y);
TMsgDlgButtons botones, HelpCtx int, 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. Además de los mismos
argumentos que la MessageDlg () función, el MessageDlgPos () permite especificar las
coordenadas utilizadas para mostrar el cuadro de diálogo. The X argument is an integer value
that specifies the distance between the left border of the screen and the left border of the
dialog box. El argumento x es un valor entero que especifica la distancia entre el borde
izquierdo de la pantalla y el borde izquierdo del cuadro de diálogo. The Y argument represents
the height from the top border of the screen to the top border of the dialog box. El argumento
de Y representa la altura del borde superior de la pantalla hasta el borde superior de la caja de
diálogo. Here is an example: Aquí está un ejemplo:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
MessageDlgPos("The right side of the main form displays " MessageDlgPos ( "El lado
derecho de la forma principal muestra"
"a \"Read-Only\" list of currently registered students.\n" "a Leer"
\-Only \ "lista de alumnos inscritos actualmente. \ n"
"This only includes students with good records.", "Esto sólo incluye a
estudiantes con buenos registros."
mtInformation, mtInformation,
TMsgDlgButtons() << mbRetry TMsgDlgButtons () <<mbRetry
<< mbIgnore, 0, 20, 120); <<0 mbIgnore,, 20, 120);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

Message Created From a Dialog Mensaje de creación de un diálogo

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. Si usted tiene un cuadro de mensaje prototipo que se está planeando utilizar una y
otra vez en su aplicación, se crea a la vez, poner en práctica, entonces el uso en lugares
diferentes en su aplicación. Such a common message box is created using the
CreateMessageDialog() function. Este cuadro de mensaje común se crea mediante el
CreateMessageDialog () la función. The CreateMessageDialog() function does not allow
you to create a new message box. El CreateMessageDialog () no le permite crear un cuadro
de mensaje nuevo. It provides a technique of creating a central dialog box that combines the
arguments and flags of the other message boxes. Proporciona una técnica de creación de un
cuadro de diálogo central que combina los argumentos y las banderas de las cajas de

16
Darwin Durand Morillo
ALGORITMOS II

mensajes. The syntax of the CreateMessageDialog() function is: La sintaxis de la


CreateMessageDialog () es:

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


__fastcall CreateMessageDialog (const AnsiString Msg,
TMsgDlgType IconType, TMsgDlgType IconType,
TMsgDlgButtons ButtonType); TMsgDlgButtons ButtonType);

This function takes three arguments similar to those of the MessageDlg() function. Esta
función tiene tres argumentos similares a los de la MessageDlg () la función. You construct it
by specifying the string message, the icon type, and the button type. A construir especificando
el mensaje de cadena, el tipo de icono, y el tipo de botón. To create this dialog box, assign its
construction to a dynamic form. Para crear este cuadro de diálogo, asignar su construcción a
una forma dinámica. 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. Para ello, puede crear una
forma local en una función o evento, pero desde un control de dinámica local es accesible
únicamente en el evento o función en la que se crea, esto sería engañar a los efectos de utilizar
el CreateMessageDialog función (). 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: Por lo tanto,
declarar una instancia de la clase TForm en las secciones públicas o privadas de la unidad o la
forma que utiliza el cuadro de mensaje:

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

private: // User declarations privado: / / declaraciones de usuario


TForm* Mine; TForm * Minas;

17
Darwin Durand Morillo
ALGORITMOS II

public: // User declarations public: / / declaraciones de usuario


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

Next, use the new operator to specify the owner of the form: A continuación, utilice el nuevo
operador para especificar el propietario de la forma:

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

To create the custom message box, assign the return value of the CreateMessageDialog()
function by creating it. Para crear el cuadro de mensaje personalizado, asignar el valor de
retorno de la CreateMessageDialog () funciona mediante la creación de ella. The message
box can be as simple as a single string, an icon, and a button: El cuadro de mensaje puede ser
tan simple como una única cadena, un icono, y un botón:

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

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


CreateMessageDialog ( "cuadro de diálogo personalizado mtWarning",,
TMsgDlgButtons() << mbYes); TMsgDlgButtons ()
<<mbYes);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

The message could also comport any of the available icons combined with any common
buttons: El mensaje también puede comportarse cualquiera de los iconos disponibles en
combinación con los botones comunes:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
__fastcall TForm1::TForm1(TComponent* Owner) __fastcall TForm1:: TForm1 (TComponent *
Owner)
: TForm(Owner) : TForm (Propietario)

18
Darwin Durand Morillo
ALGORITMOS II

{(
Mine = new TForm(this); Mine = TForm nuevo (este);
Mine = CreateMessageDialog("Is this the best song or what?", Mine =
CreateMessageDialog ( "¿Es esta la mejor canción o qué?",
mtInformation, mtInformation,
TMsgDlgButtons() << mbYes << mbAbort TMsgDlgButtons
() <<mbYes <<mbAbort
<< mbCancel << mbNo); <<MbCancel <<mbNo);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

With the message box created, you can call it from any section or control that needs it in your
application: Con el cuadro de mensaje creado, usted puede llamar desde cualquier sección o de
control que necesita en su aplicación:

#include <vcl.h> # include <vcl.h>


#include "Unit1.h" # include "Unit1.h"
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
#pragma package(smart_init) # pragma package (smart_init)
#pragma resource "*.dfm"TForm1 *Form1; # pragma resource "*. dfm" TForm1
* Form1;
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
__fastcall TForm1::TForm1(TComponent* Owner) __fastcall TForm1:: TForm1
(TComponent * Owner)
: TForm(Owner) : TForm (Propietario)
{(
Mine = new TForm(this); Mine = TForm nuevo (este);
Mine = CreateMessageDialog("Is this the best song or what?", Mine =
CreateMessageDialog ( "¿Es esta la mejor canción o qué?",
mtInformation, mtInformation,
TMsgDlgButtons() << mbYes << mbAbort
TMsgDlgButtons () <<mbYes <<mbAbort
<< mbCancel << mbNo); <<MbCancel
<<mbNo);
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1::
Button1Click (TObject * Sender)
{(
Mine->ShowModal(); Mine-> ShowModal ();
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
void __fastcall TForm1::Button2Click(TObject *Sender) void __fastcall TForm1::
Button2Click (TObject * Sender)
{(
Mine->ShowModal(); Mine-> ShowModal ();
})
//--------------------------------------------------------------------------- //-----------

19
Darwin Durand Morillo
ALGORITMOS II

------------------------------------- ---------------------------
void __fastcall TForm1::Panel1Click(TObject *Sender) void __fastcall TForm1::
Panel1Click (TObject * Sender)
{(
Mine->ShowModal(); Mine-> ShowModal ();
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------

The Input Dialog Box El cuadro de diálogo de entrada

The InputBox() function allows you to display a message box that would request a piece of
information from the user. La caja de texto () función le permite mostrar un cuadro de
mensaje que se pediría a un pedazo de información del usuario. The message box is equipped
with an edit box and two buttons. El cuadro de mensaje está equipado con un cuadro de edición
y dos botones. The edit box accepts a string from the user. El cuadro de edición acepta una
cadena del usuario. The user can type anything but it is up to you to use the content of that
edit box as your program needs it. El usuario puede escribir nada, pero es a usted a utilizar el
contenido de esa caja de edición como el programa necesita. When the user clicks OK, the
Input Box returns the content of its edit box. Cuando el usuario hace clic en Aceptar, el cuadro
de entrada se muestra el contenido de su cuadro de edición. If the user clicks Cancel or presses
Esc, the content of its edit box is dismissed. Si se desestima el usuario hace clic en Cancelar o
presiona ESC, el contenido de su caja de edición.

The syntax of the InputBox() function is La sintaxis de la InputBox () es

AnsiString __fastcall InputBox(const AnsiString Caption , AnsiString __fastcall InputBox (const


AnsiString Leyenda,
const AnsiString Prompt , const AnsiString Default ); const
AnsiString del sistema, const AnsiString defecto);

The Caption argument specifies the string that would display on the title bar of the dialog box.
El argumento Leyenda especifica la cadena que aparece en la barra de título del cuadro de
diálogo. The Prompt is a sentence that would display to the user as to what to type in the
provided edit box. El símbolo es una frase que mostrar al usuario en cuanto a qué tipo previsto
en el cuadro de edición. The Default argument is a suggested value you can display in the edit
box to guide the user as the type of value expected. El argumento por defecto es un valor
sugerido se puede visualizar en el cuadro de edición de la guía del usuario como el tipo de valor
esperado. If you do not want to specify a default value, you can set its string value to empty. Si
no desea especificar un valor predeterminado, puede establecer su valor de cadena vacía. Here
is example: Aquí es un ejemplo:

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

20
Darwin Durand Morillo
ALGORITMOS II

InputBox("Distance and Measurement", InputBox ( "Distancia y medición",


"Enter the distance in kilometer:", ""); "Introduzca la distancia en kilómetros:",
"");
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

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. Si se especifica el argumento
predeterminado y el usuario hace clic en Aceptar sin cambiar el contenido de la caja de edición,
el compilador consideraría el valor por defecto como válida. After using the dialog box, the user
would click OK, press Enter, click Cancel, or press Esc. Después de usar el cuadro de diálogo, el
usuario haga clic en Aceptar, presione Enter, haga clic en Cancelar o presione ESC. If the user
clicks OK or presses Enter, the function returns the value that the user would have typed in the
edit box. Si el usuario hace clic en Aceptar o presiona Intro, la función devuelve el valor que el
usuario ha escrito en el cuadro de edición. This allows you to write a conditional statement that
would consider the new value returned by clicking OK on the InputBox dialog: Esto le permite
escribir una sentencia condicional que considerar el nuevo valor devuelto, haga clic en Aceptar
en el cuadro de diálogo InputBox:

//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) void __fastcall TForm1:: Button1Click
(TObject * Sender)
{(
Edit1->Text = InputBox("Distance and Measurement", Edit1-> Text = InputBox
( "Distancia y medición",
"Enter the distance in kilometer:", ""); "Introduzca la distancia en
kilómetros:", "");
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

If the user clicks Cancel or presses Esc, whatever the edit box was displaying would be ignored.
Si el usuario hace clic en Cancelar o presiona Esc, cualquiera que sea el cuadro de edición
mostraba sería ignorado. But the function would still return the default value. Pero la función
aún se devolverá el valor por defecto. If the returned value is intended for mathematical, date,
or time calculations, you should convert it accordingly. Si el valor devuelto se destina para
realizar operaciones matemáticas, la fecha o la hora cálculos, se deben convertir en
consecuencia.

Practical Learning: Using the InputBox Dialog De aprendizaje práctico: Uso del
cuadro de diálogo InputBox

1. Add a button Agregar un botón to the form a la forma


2. Double-click it. Haga doble clic en él. Press Tab and type Presione la tecla Tab y el tipo de

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


( "Student Registration", "Tipo de Género del Estudiante", "");
3. Press F9 to test the form. Presione F9 para probar el formulario. Click the new button.
Haga clic en el botón Nuevo. Notice that the content of its edit box is empty Observe que
el contenido de su cuadro de edición está vacía

21
Darwin Durand Morillo
ALGORITMOS II

4. Close the Input Box and the form Cierre el cuadro de entrada y la forma

The InputQuery Request La solicitud InputQuery

Like the InputBox() function, the InputQuery() function is used to display a prompting
dialog box to the user. Al igual que el InputBox () función, el InputQuery () se utiliza para
mostrar un cuadro de diálogo que pide al usuario. The syntax of this function is: La sintaxis de
esta función es:

extern PACKAGE bool __fastcall InputQuery(constAnsiString ACaption, extern bool PAQUETE


__fastcall InputQuery (ACaption constAnsiString,
const AnsiString APrompt, const AnsiString
APrompt,
AnsiString &Value); AnsiString & Value);

This takes three strings. Esto tiene tres cuerdas. The Caption parameter is a string that displays
on the title bar of the dialog box. Leyenda El parámetro es una cadena que aparece en la barra
de título del cuadro de diálogo. The Prompt parameter is the sentence that indicates to the user
what to type in the edit box. El parámetro del sistema es la frase que indica al usuario qué tipo
en el cuadro de edición. Like the InputBox() function, the Value parameter provides a default
and sample value to the user. Al igual que el InputBox () función, el parámetro de valor por
defecto y proporciona un valor de ejemplo para el usuario. Like the InputBox() function, the
user can type a new value. Al igual que el InputBox () función, el usuario puede escribir un
nuevo valor. Here is an example of using the InputQuery() function: He aquí un ejemplo del
uso de la InputQuery () Función:

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

InputQuery("Exiting Application", InputQuery ( "Salir de la aplicación",


"Are you sure you want to exist (y=Yes/n=No)?", "¿Estás seguro de que desea
existir (Y = Yes / n = n)?",
Value); Value);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------

Unlike the InputBox() function that returns a string, the InputQuery() function returns two
values. A diferencia de la InputBox () que devuelve una cadena, el InputQuery () devuelve
dos valores. By its declaration, this function returns a Boolean value of true or false. En su
declaración, esta función devuelve un valor booleano de verdadero o falso. If the user clicks OK
or presses Enter after using the dialog box, the function returns true. Si el usuario hace clic en
Aceptar o presiona Enter después de usar el cuadro de diálogo, la función devuelve cierto. If
the user presses Esc or clicks Cancel, the function returns false. Si el usuario pulsa Esc o hace
clic en Cancelar, la función devuelve falso.

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. Si el usuario hace clic en Aceptar (o presiona Enter), al igual que
el InputBox () la función, si el usuario ha cambiado el valor de la caja de edición o no, el
contenido de la caja de edición, siempre que el argumento del valor, sería devuelto. Because
Value is passed by reference, the function can return two values. Porque el valor se pasa por

22
Darwin Durand Morillo
ALGORITMOS II

referencia, la función puede retornar dos valores. 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. A diferencia de la InputBox () la función, si el usuario hace clic en Cancelar
(o presiona Esc) después de lidiar con el cuadro de diálogo, el valor del argumento de valor se
ignora.

You can validate the returned value of Value by writing a conditional statement that examines
whether the user had clicked OK or Cancel. Usted puede validar el valor devuelto de valor por
escrito una sentencia condicional que examina si el usuario hubiera hecho clic en Aceptar o
Cancelar. 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: En el siguiente ejemplo, cuando el usuario hace
clic en un botón en el formulario, el compilador comprueba si el usuario ha hecho clic en
Aceptar, en cuyo caso sería mostrar el valor que devuelve el argumento de valor en un control
de edición de la forma:

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

if( InputQuery("Exiting Application", if (InputQuery ( "Salir de la aplicación",


"Are you sure you want to exist (Y=Yes/Y=No)?", "¿Está
seguro de que desea que exista (Y = Yes / Y = n)?",
Answer) == True ) Respuesta) == true)
Edit1->Text = Answer; Edit1-> Text = Respuesta;
})
//--------------------------------------------------------------------------- //------------
------------------------------------ ---------------------------

23

También podría gustarte