问题的提出(感谢 forgot (让一切随风) 提出这个问题):
利用Rtti技术,把某一个控件的一些指定的公用的可以在运行期修改的属性赋予另一个同类控件,函数原型如下:
CloneProperty(SourceComp,TargetComp:TComponent;Properties:TStrings):Boolean;
参数:SourceComp:源控件;
TargetComp:目标控件;
Properties:要克隆的属性字符串列表;
Boolean:如果克隆成功返回True,否则为False;
举例:
Properties中的String依次为'Caption','Hint','Left','Tag'
调用:CloneProperty(Button1,Button2,Properties)?
/// 克隆对象属性,作者:Kingron,特别鸣谢ZsWang!
uses TypInfo ;
function CloneProperty ( SourceComp , TargetComp : TObject ; Properties : array of string ): Boolean ;
var
i : integer ;
begin
Result := True ;
try
for i := Low ( Properties ) to High ( Properties ) do
begin
if not IsPublishedProp ( SourceComp , Properties [ I ]) then Continue ;
if not IsPublishedProp ( TargetComp , Properties [ I ]) then continue ;
if PropType ( SourceComp , Properties [ I ]) <> PropType ( TargetComp , Properties [ I ]) then
Continue ;
case PropType ( SourceComp , Properties [ i ]) of
tkClass :
SetObjectProp ( TargetComp , Properties [ i ], GetObjectProp ( SourceComp , Properties [ i ]));
tkMethod :
SetMethodProp ( TargetComp , Properties [ I ], GetMethodProp ( SourceComp ,
Properties [ I ]));
else
SetPropValue ( TargetComp , Properties [ i ], GetPropValue ( SourceComp , Properties [ i ]));
end ;
end ;
except
Result := False ;
end ;
end ;
procedure TForm1 . Button1Click ( Sender : TObject );
begin
CloneProperty ( Button1 , Button2 , [ 'Left' , 'Font' , 'PopupMenu' , 'OnClick' ]);
ShowMessage ( 'OK' );
end ;
kingron: How I can copy Whole Object? (10.09.2002 03:45:49)
--------------------------------------------------------------------------------
How I can copy Whole Object? from kingron
Russar ask "How I can copy Whole Object?"
A: Please use CloneProperty2 to do it.
uses
TypInfo;
{ Clone Object! Coder:Kingron }
function CloneProperty2(SourceComp, TargetComp: TObject): Boolean;
var
i : Integer;
Properties : PPropList;
begin
Result := True;
try
for i := 0 to GetPropList(SourceComp, Properties) - 1 do
begin
if LowerCase(Properties[i].Name) = 'name' then continue;///do nothing for "Name".....
if not IsPublishedProp(SourceComp, Properties[I].Name) then Continue;
if not IsPublishedProp(TargetComp, Properties[I].Name) then Continue;
if PropType(SourceComp, Properties[I].Name) <> PropType(TargetComp, Properties[I].Name)
then
Continue;
case PropType(SourceComp, Properties[i].Name) of
tkClass:
SetObjectProp(TargetComp, Properties[i],
GetObjectProp(SourceComp, Properties[i]));
tkMethod:
SetMethodProp(TargetComp, Properties[I], GetMethodProp(SourceComp,
Properties[I]));
else
SetPropValue(TargetComp, Properties[i].Name, GetPropValue(SourceComp,
Properties[i].Name));
end;
end;
except
Result := False;
end;
end;