Delphi Source Code
Search engine
HOME Components Tutorials Add Trick Links Contacts
ActiveX Components Database Files Forms Graphic Internet/Lan Math Miscellaneous Multimedia Printing Strings System Information Windows

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]
Delphi Tricks
Delphi Tricks
For any problems or recommendations about Delphi Tricks site, please

feel free to contact us on that e-mail: support@delphitricks.com.
If you want to advertise on the site use that e-mail: advertise@delphitricks.com.

You can freely use or modify these Delphi source codes for non-commercial use. We are not responsible of any damages that can be caused by the utilisation of that source codes.

Copyright © 2006 AVSoftware Company. All rights reserved.