| Delphi Tutorial for "Create component or form at runtime" |
Page:
[1] Create component or form at runtime
1. You have to register it:
//For example:
RegisterClass( TButton );
Form types can be registered in their units initialization
section. As long as the unit is used the form will be
registered.
2. To create the class first get a class refrence to it using
the FindClass or GetClass function:
var MetaClass : TPersistentClass;
MetaClass := FindClass( 'TForm2');
3. Before creating an instance, cast the MetaClass to the
general type that it is, otherwise you will not be able
to call the correct constructor (so you won't be able
to specify any required parameters).
var ComponentMetaClass : TComponentClass;
ComponentMetaClass := TComponentClass( MetaClass );
4. Now the constructor can be called:
var AForm: TComponent;
AForm := ComponentMetaClass.Create( self );
5. AForm now contains a valid instance of the class
specified in the call to FindClass(). Methods of the
component can be called. By typecasting the instance
to the correct class or a valid base class (if you know
it), you can call methods of the object.:
TForm(AForm).Show;
or
var SomeForm : TForm;
SomeForm := TForm( AForm );
SomeForm.Show;
The entire process in a button click:
procedure TForm1.Button1Click(Sender: TObject);
var MetaClass : TPersistentClass;
ComponentMetaClass : TComponentClass;
AForm: TComponent;
begin
MetaClass := FindClass( 'TForm2');
ComponentMetaClass := TComponentClass( MetaClass );
AForm := ComponentMetaClass.Create( self );
TForm(AForm).Show;
end;
This entire procedure can be handled with one line of code:
TFormTForm( TComponentClass( FindClass( 'TForm2' ) ).Create( Self )).Show;
Page:
[1]
|
|