Example VCL programming techniques
This little (a bit stupid) application shows some of the
OOP and VCL techniques as discussed in the OOP and VCL papers.
This application uses :
- Class references to create controls
- RTTI RunTime Type Information As and Is
This application has a radiogroup in which the class TheClass of
TControlclass is assigned to a specific class.
With this information the appropriate object is made with button btnCreate.
Buttons get also a onclick event.
Related papers Dutch :
OOP
VCL
Related papers english :
OOP
VCL
Download
here the source of this example
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
RadioGroup1: TRadioGroup;
btnCreate: TButton;
GroupBox1: TGroupBox;
procedure FormCreate(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
procedure btnCreateClick(Sender: TObject);
procedure ControlClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
x, y : integer; //For positioning the controls
end;
var
Form1: TForm1;
aControl : TControl;
TheClass : TControlClass; //The Class reference
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
x := 184;
y := 16;
RadioGroup1.ItemIndex := 0;
end;
//Set the class references
procedure TForm1.RadioGroup1Click(Sender: TObject);
begin
Case RadioGroup1.ItemIndex of
0 : TheClass := TButton;
1 : TheClass := TRadioButton;
2 : TheClass := TCheckbox;
3 : TheClass := TEdit;
end;
end;
// create the control using the current classref
// and give it a name, notice that the name is automatic the caption
procedure TForm1.btnCreateClick(Sender: TObject);
begin
x := x + 2; //Position the new control
y := y + 25;
aControl := TheClass.Create(Self);
aControl.Parent := GroupBox1;
aControl.Left := x;
aControl.Top := y;
aControl.Name := aControl.ClassName + IntToStr(x)+IntToStr(y);
// Give the Buttons a OnClick event
if aControl is TButton then
(aControl as TButton).OnClick := ControlClick; //Assign an onclick event
end;
// The Control onClick event for buttons
procedure TForm1.ControlClick(Sender: TObject);
begin
aControl := Sender as TButton; // Set aControl object to the current clicked button
ShowMessage('Clicked a control of class ' + aControl.name);
end;
end.
|