Documentos de Académico
Documentos de Profesional
Documentos de Cultura
ALGORITMOS II
MessageBox
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.
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.
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
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.";
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.");
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
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
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:
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
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:
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";
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
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:
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:
11
Darwin Durand Morillo
ALGORITMOS II
12
Darwin Durand Morillo
ALGORITMOS II
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:
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:
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.
14
Darwin Durand Morillo
ALGORITMOS II
15
Darwin Durand Morillo
ALGORITMOS II
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);
})
//--------------------------------------------------------------------------- //----------------------------
-------------------- ---------------------------
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
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);
17
Darwin Durand Morillo
ALGORITMOS II
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);
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:
19
Darwin Durand Morillo
ALGORITMOS II
------------------------------------- ---------------------------
void __fastcall TForm1::Panel1Click(TObject *Sender) void __fastcall TForm1::
Panel1Click (TObject * Sender)
{(
Mine->ShowModal(); Mine-> ShowModal ();
})
//--------------------------------------------------------------------------- //-----------
------------------------------------- ---------------------------
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 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
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
21
Darwin Durand Morillo
ALGORITMOS II
4. Close the Input Box and the form Cierre el cuadro de entrada y la forma
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:
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;
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;
23