User: alciro    User
 

Programación en C++ Builder

Share |
 Arrays (matrices)
 Punteros
3. Ejemplo de clase en c++
8. Métodos de la clase AnsiString
 Proyectos en C++
 Packages, distribuir una aplicación sin instalación
 Ordenación por intercambio o burbuja
 Funciones de cadenas de caracteres string.h

11. Eventos de los formularios

11.1. Derivados de TCustomForm

OnActivate

Este evento se produce cuando el formulario se crea o cuando se cambia de un formulario a otro dentro de la aplicación. Para detectar cuando se pasa de otra aplicación a la nuestra se utiliza el evento OnActivate del objeto Taplication.

__property Classes::TNotifyEvent OnActivate = {read=FOnActivate, write=FOnActivate, stored=IsForm};

The following code adds the caption of Form2 to a list box in Form1 when a Form2 is activated.

#include "Unit1.h" //so we can refer to Form1.

void __fastcall TForm2::FormActivate(TObject *Sender)
{
	Form1->ListBox1->Items->Add(Screen->ActiveForm->Caption);
}


OnClose

Al cerrar el formulario se produce el evento OnClose. Éste hace una llamada al evento OnCloseQuery para comprobar si es correcto cerrar el formulario. Si OnCloseQuery devuelve el valor false, el formulario no se cierra.

enum TCloseAction { caNone, caHide, caFree, caMinimize };
typedef void __fastcall (__closure *TCloseEvent)(System::TObject* Sender, TCloseAction &Action);
__property TCloseEvent OnClose = {read=FOnClose, write=FOnClose, stored=IsForm};

El formulario se cierra mediante el método Close().

El TcloseEvent indica al método la forma de cerrar el formulario. El valor de los parámetros de la variable Action determina si el formulario se cierra.

AccionesDescripción
caNoneEl formulario no está preparado para ser cerrarlo.
caHideEl formulario no se cierra, pero queda oculto. La aplicación aún puede acceder al formulario
CaFreeEl formulario se cierra y la memoria que ocupaba quede libre.
CaMinimizeEl formulario se minimiza, antes de cerrarlo. Este es la acción por defecto para los formularios MDI hijos.

This example displays a message dialog box when the user attempts to close the form. If the user clicks the Yes button, the form closes; otherwise, the form remains open.

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
if(Application->MessageBox("Close application ?", "Close?", MB_YESNO) == mrYes)
	Action = caFree;
else
	Action = caNone;
}


OnCloseQuery

Ocurre cuando el método Close es llamado o cuando el usuario actúa sobre el icono de cerrar de la barra del formulario.

typedef void __fastcall (__closure *TCloseQueryEvent)(System::TObject* Sender, bool &CanClose);
__property TCloseQueryEvent OnCloseQuery = {read=FOnCloseQuery, write=FOnCloseQuery, stored=IsForm};

La variable CanClose determina si el formulario puede ser cerrado. El valor por defecto es true.

Por ejemplo, se puede utiliza el evento OnCloseQuery para guardar un documento en un fichero antes de cerrar el formulario.

When the user attempts to close the form in this example, a message dialog appears that asks the user if it is OK to close the form. If the user chooses the Yes button, the form closes. If the user chooses Cancel or No, the form doesn't close.

void __fastcall TForm1::FormCloseQuery(TObject *Sender, bool &CanClose)
{
if(Application->MessageBox("Close the form?", "Close?", MB_YESNOCANCEL) != mrYes)
	CanClose = false;
}


OnCreate

Ocurre cuando el formulario es creado por primera vez. Con éste evento se realizan todas las tareas previas necesarias para el funcionamiento del formulario. Sólo se produce un evento OnCreate por cada formulario.

__property Classes::TNotifyEvent OnCreate = {read=FOnCreate, write=FOnCreate, stored=IsForm};

This very simple OnCreate event handler assures that the form is the same color as the Windows system color of your application workspace:

void __fastcall TForm1::FormCreate(TObject *Sender)
{
Color = clAppWorkSpace;
}

Note: The Color property in this example is not prefaced with the name of the form. If you write the statement like this,

Form1->Color = clAppWorkSpace;

the application won't run without error, because Form1 does not yet exist at the time this code is executed


OnDeactivate

Ocurre cuando el formulario pierde el foco. Este evento se utiliza para controlar la transición del formulario que se encuentra activo a otro formulario de la misma aplicación. Cuando se pasa de nuestra aplicación a otra, este evento no se produce. Para controlar el paso de aplicación, se usa el evento OnDeactivate del objeto Taplication.

__property Classes::TNotifyEvent OnDeactivate = {read=FOnDeactivate, write=FOnDeactivate, stored=IsForm};


OnDestroy

Evento opuesto a OnCreate. Se utiliza para liberar la memoria que asigne dinámicamente un formulario, o para las tareas de limpieza.

__property Classes::TNotifyEvent OnDestroy = {read=FOnDestroy, write=FOnDestroy, stored=IsForm};

The following code dynamically creates a button called BtnMyButton with the Caption "My Button". The memory associated with the button is deleted when the form is destroyed.

__fastcall TForm1::TForm1(TComponent* Owner)

: TForm(Owner)
{
BtnMyButton = new TButton(this);
BtnMyButton->Parent = this;
BtnMyButton->Caption = "My Button";
}
//------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
delete BtnMyButton;
}

 

Orden de los eventos al crear y destruir un Formulario

Desde que el formulario es creado y la propiedad Visible es true, ocurren los siguientes eventos por orden de lista:

OrdenEventosUso
1OnCreateTareas previas necesarias para el funcionamiento del formulario.
2OnShowProceso que necesite el formulario antes de hacerse visible.
3OnActivateCuando se cambia de un formulario a otro dentro de la aplicación.
4OnPaintCuando el formulario se tiene que redibujar.

Desde que el formulario se cierra y se libera la memoria, ocurren los siguientes eventos por orden de lista:

OrdenEventosUso
1OnCloseQueryGuardar un documento en un fichero antes de cerrar el formulario.
2OnCloseMirar si es correcto que se cierre un formulario.
3OnDeactivateTransición del formulario que se encuentra activo a otro formulario
4OnDestroyPara las tareas de limpieza


OnHelp

Ocurre cuando el formulario recibe una petición de ayuda.

typedef bool __fastcall (__closure *THelpEvent)(Word Command, int Data, bool &CallHelp);
__property Classes::THelpEvent OnHelp = {read=FOnHelp, write=FOnHelp};


OnHide

Ocurre cuando el formulario es ocultado (cuando la propiedad Visible se establece a false)

__property Classes::TNotifyEvent OnHide = {read=FOnHide, write=FOnHide, stored=IsForm};

This example uses two forms, each with a label and a button. When the user clicks a button, the other form appears and the current form disappears. Also, a message appears in the label of the form that is showing, indicating that the other form is hidden. This is the implementation section of Unit1:

#include "Unit2.h"

//------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Form2->Show();
Hide();
}
//------------------------------------------------------------------
void __fastcall TForm1::FormHide(TObject *Sender)
{
Form2->Label1->Caption = "Form1 is hiding";
}

This is the implementation section of Unit2:

#include "Unit1.h"
//------------------------------------------------------------------
#pragma resource "*.dfm"
TForm2 *Form2;
//------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
}
//------------------------------------------------------------------
void __fastcall TForm2::Button1Click(TObject *Sender)
{
Form1->Show();
Hide();

}
//------------------------------------------------------------------
void __fastcall TForm2::FormHide(TObject *Sender)
{
Form1->Label1->Caption = "Form2 is hiding";
}


OnPaint

Ocurre cuando el formulario se tiene que redibujar. Cuando se tiene que mostrar un objeto constantemente en un formulario, o como consecuencia de un cambio de tamaño del formulario.

__property Classes::TNotifyEvent OnPaint = {read=FOnPaint, write=FOnPaint, stored=IsForm};

The following code loads a background bitmap onto the Canvas of the main form in the OnPaint event handler. In the header file for Unit 1. add a private member to TForm1 of type Graphics::TBitmap named TheGraphic;

void __fastcall TForm1::FormPaint(TObject *Sender)// OnPaint event handler
{
Form1->Canvas->Draw(0, 0, TheGraphic); // Draw the graphic on the Canvas
}
void __fastcall TForm1::FormCreate(TObject *Sender)// OnCreate event handler
{
TheGraphic = new Graphics::TBitmap(); // Create the bitmap object
TheGraphic->LoadFromFile("C:\APP\BKGRND.BMP"); // Load the bitmap from a file
}


OnResize

Se activa cada vez que se modifica el tamaño del formulario. Se utiliza este evento para adecuar la posición de los componentes sobre el formulario o para redibujarlo.

__property Classes::TNotifyEvent OnResize = {read=FOnResize, write=FOnResize, stored=IsForm};

The following code keeps the right edge on Button1 against the right edge of Form1 when Form1 is resized.

void __fastcall TForm1::FormResize(TObject *Sender)
{
Button1->Left = Form1->ClientWidth - Button1->Width;
}


OnShow

Ocurre justo antes de que el formulario sea visible (cuando la propiedad Visible se pone a true). Puede utilizarse este evento para realizar cualquier proceso que necesite el formulario antes de hacerse visible.

__property Classes::TNotifyEvent OnShow = {read=FOnShow, write=FOnShow, stored=IsForm};

This example colors the form and changes its caption when it becomes visible:

void __fastcall TForm1::FormShow(TObject *Sender)
{
Color = clLime;
Caption = "I am showing";
}
Loading

copyright © 2007-2024  www.alciro.org  All rights reserved.         
Share |