home *** CD-ROM | disk | FTP | other *** search
- unit Dynamain;
-
- { This unit demonstrates the use of class references to dynamically
- instantiate components. }
-
- interface
-
- uses
- SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
- Forms, Dialogs, ExtCtrls, StdCtrls;
-
- type
- TForm1 = class(TForm)
- CreationArea: TPanel;
- Panel1: TPanel;
- GroupBox1: TGroupBox;
- Label1: TLabel;
- Label2: TLabel;
- Label3: TLabel;
- Label4: TLabel;
- ClassList: TComboBox;
- XPos: TEdit;
- YPos: TEdit;
- Button1: TButton;
- TextProp: TEdit;
- procedure FormCreate(Sender: TObject);
- procedure Button1Click(Sender: TObject);
- private
- { Private declarations }
- public
- { Public declarations }
- end;
-
- var
- Form1: TForm1;
-
- implementation
-
- {$R *.DFM}
-
- { In the form's OnCreate method, we fill the combo box with a list
- of class names, each accompanied by an actual class reference
- (stored in Items.Objects). }
-
- procedure TForm1.FormCreate(Sender: TObject);
- begin
- with ClassList.Items do
- begin
- AddObject('TEdit', TObject(TEdit));
- AddObject('TCheckBox', TObject(TCheckBox));
- AddObject('TRadioButton', TObject(TRadioButton));
- AddObject('TButton', TObject(TButton));
- AddObject('TListBox', TObject(TListBox));
- end;
- ClassList.ItemIndex := 0;
- end;
-
- { When the Create button is pressed, we fetch the class reference from
- the currently selected itm in the combo box. We can then create an
- actual instance of whatever class the reference points to by calling its
- constructor. We then parent the new instance to a panel, and position it
- according to the values in the edit boxes.
-
- Lastly, we send a WM_SETTEXT message to the control (as long as it is a
- TWinControl) and allow the control to handle the message however it wants.
- (Some controls have a Caption property, while others have a Text property.
- Sending a WM_SETTEXT message avoids having to know which property the new
- instance has.) }
-
- procedure TForm1.Button1Click(Sender: TObject);
- var
- Reference: TControlClass;
- Instance: TControl;
- Text: array[0..255] of Char;
- begin
- Reference := TControlClass(ClassList.Items.Objects[ClassList.ItemIndex]);
-
- Instance := Reference.Create(Self);
- Instance.Parent := CreationArea;
- Instance.Left := StrToInt(XPos.Text);
- Instance.Top := StrToInt(YPos.Text);
-
- if Instance is TWinControl then
- SendMessage(TWinControl(Instance).Handle, WM_SETTEXT, 0,
- Longint(StrPCopy(Text, TextProp.Text)));
- end;
-
- end.
-