19 Mei 2009

Implementasi Run-Time Type Information / RTTI (Bagian 3)

Dengan mengetahui manfaat dari RTTI, kita bisa menggunakan fungsi-fungsi yang ada untuk mengubah properti dari komponen VCL yang ada pada sebuah form. Kita bisa mengubah properti yang mempunyai tipe integer, string, boolean, atau bahkan enumerasi. Contoh skrip ini minimum membutuhkan sebuah form (nama Form1) dan sebuah TEdit (nama Edit1). Parameter yang dibutuhkan adalah nama form, nama obyek/komponen, nama properti dan nilai dari properti.
uses Forms, StrUtils, SysUtils, TypInfo;

procedure SetObjectProperty(const aFormName, aObjectName, aPropName: string; aPropValue: Variant);
var
  frm: TForm;
  obj: TObject;
  i, j: Integer;
begin
  frm := nil;
  for i := 0 to Screen.FormCount - 1 do
    if UpperCase(Screen.Forms[i].Name) = UpperCase(aFormName) then
      frm := Screen.Forms[i];
  if (Assigned(frm)) and (frm.Name = aFormName) then
  begin
    obj := frm.FindComponent(aObjectName);
    j := 1;
    i := PosEx('.', aPropName, j);
    while i > 0 do
    begin
      obj := GetObjectProp(obj, Copy(aPropName, j, i - j));
      j := i + 1;
      i := PosEx('.', aPropName, j);
    end;
    SetPropValue(obj, Copy(aPropName, j, Length(aPropName)), aPropValue);
  end;
end;

Jalankan perintah-perintah berikut dan lihat hasilnya.
SetObjectProperty('Form1', 'Edit1', 'Text', 'Tes 123');
SetObjectProperty('Form1', 'Edit1', 'Enabled', False);
SetObjectProperty('Form1', 'Edit1', 'Color', clRed);
SetObjectProperty('Form1', 'Edit1', 'Font.Size', 12);
SetObjectProperty('Form1', 'Edit1', 'Font.Style', '[fsBold,fsItalic]');

Tidak ada komentar:

Posting Komentar