如何查看应用程序中是否已经存在Delphi组件?
如何测试当前应用程序中是否存在组件?例如,如果创建名为radiogroup 1的动态radiogroup,如何检查是否已经存在名为radiogroup 1的组件?首先,您必须列出应用程序中的所有表单 然后,您必须使用如何查看应用程序中是否已经存在Delphi组件?,delphi,components,Delphi,Components,如何测试当前应用程序中是否存在组件?例如,如果创建名为radiogroup 1的动态radiogroup,如何检查是否已经存在名为radiogroup 1的组件?首先,您必须列出应用程序中的所有表单 然后,您必须使用FindComponent 下面是一些示例代码: 大概是这样的: function TForm1.FindMyComponent(Parent: TComponent; Name: string): TComponent; var i: integer; begin if P
FindComponent
下面是一些示例代码: 大概是这样的:
function TForm1.FindMyComponent(Parent: TComponent; Name: string): TComponent;
var
i: integer;
begin
if Parent.ComponentCount = 0 then exit(nil);
Result:= Parent.FindComponent(Name);
if Assigned(Result) then Exit;
for i:= 0 to Parent.ComponentCount do begin
Result:= FindMyComponent(Parent.Components[i], Name);
if Assigned(Result) then Exit;
end; {for i}
end;
procedure TForm1.Test;
var
MyRadioGroup: TComponent;
begin
MyRadioGroup:= FindMyComponent(Application, 'RadioGroup1');
....
end;
如果你这样称呼它:
function TForm1.FindMyComponent(Parent: TComponent; Name: string): TComponent;
var
i: integer;
begin
if Parent.ComponentCount = 0 then exit(nil);
Result:= Parent.FindComponent(Name);
if Assigned(Result) then Exit;
for i:= 0 to Parent.ComponentCount do begin
Result:= FindMyComponent(Parent.Components[i], Name);
if Assigned(Result) then Exit;
end; {for i}
end;
procedure TForm1.Test;
var
MyRadioGroup: TComponent;
begin
MyRadioGroup:= FindMyComponent(Application, 'RadioGroup1');
....
end;
它将递归地查看应用程序中为您的radiogroup注册的所有表单。
见:
请注意,搜索不区分大小写
自己记账当然,如果您以这种方式寻找大量控件,那么这段代码将非常慢。
正如David所说,将名称附加到以编程方式创建的控件是没有意义的。最好在字典中保留一个控件名列表,并以这种方式引用它们
type
TControlClass = class of TControl;
TForm1 = class(TForm)
private
NewIndex: TDictonary<string, integer>;
AllControls: TDictonary<string, TControl>;
....
function TForm1.AddControl(NewControl: TControl);
var
ClassName: string;
Index: integer;
ControlName: string;
begin
ClassName:= NewControl.ClassName;
if not(NewIndex.TryGetValue(ClassName, Index) then Index:= 0;
Inc(Index);
NewIndex.AddOrSetValue(ClassName, Index);
ControlName:= ControlName + IntToStr(Index);
NewControl.Name:= ControlName; //optional;
AllControls.Add(ControlName, NewControl);
end;
类型
TControlClass=TControl的类别;
TForm1=类(TForm)
私有的
新指标:TDictonary;
所有对照组:t对照组;
....
函数TForm1.AddControl(NewControl:TControl);
变量
类名:string;
索引:整数;
ControlName:字符串;
开始
ClassName:=NewControl.ClassName;
如果不是(NewIndex.TryGetValue(类名,索引),则索引:=0;
公司(指数),;
AddOrSetValue(类名,索引);
ControlName:=ControlName+IntToStr(索引);
NewControl.Name:=ControlName;//可选;
添加(ControlName,NewControl);
结束;
跟踪这些事情有这么难吗?人们不会在你不看的时候在你的应用程序中随机创建广播组!组件的名称有什么关系?AnyFindComponent
可能是你问的问题的答案,但对于你潜在的问题,谁知道呢。它(几乎总是)给动态创建的组件命名是毫无意义的(我想您希望避免“名为已存在的组件”异常)。您最好不给它们命名(除非您确实需要给它们命名)并通过创建时存储的引用访问它们。非常感谢您回复David Hefferman您真的解决了我的问题:)叹气。我怀疑FindComponent是否真的能拯救你。@FreeConsulting:实际上FindComponent()
的作用域是组件方面的,因为它是TComponent
的一种方法。只有当组件恰好是t表单时,它才是形式明智的。