【问题标题】:How to see if a Delphi component already exists in your application?如何查看应用程序中是否已经存在 Delphi 组件?
【发布时间】:2014-10-10 12:05:22
【问题描述】:

如何测试当前应用程序中是否存在组件,例如,如果您创建一个名为 radiogroup1 的动态无线电组,您如何检查是否已经存在名为 radiogroup1 的组件?

【问题讨论】:

  • 跟踪这些事情就这么难吗?当您不注意时,人们不会在您的应用程序中随意创建广播组!组件的名称有什么关系?任何FindComponent 都可能是您所提问题的答案,但至于您的根本问题,谁知道呢。
  • 为动态创建的组件命名(几乎总是)毫无意义(我猜您想避免 "A component named already exists" 异常)。您最好不要命名它们(除非您确实需要给它们命名)并通过创建时存储的引用来访问它们。
  • 非常感谢大卫赫弗曼的回复,你真的解决了我的问题:)
  • 叹息。我怀疑 FindComponent 真的是你的救星。
  • @FreeConsulting:实际上FindComponent() 的范围是组件方面的,因为它是TComponent 的一种方法。仅当组件恰好是 TForm 时,它才是形式明智的。

标签: delphi components


【解决方案1】:

首先,您必须列出应用程序中的所有表单。

然后您必须使用 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;

它将递归查看您的无线电组应用程序中的所有注册表格。 见:http://docwiki.embarcadero.com/Libraries/XE2/en/System.Classes.TComponent.FindComponent

请注意,搜索不区分大小写。

自己记账
当然,如果您要以这种方式查找大量控件,则此代码会很慢。
同样正如大卫所说,将名称附加到您以编程方式创建的控件上是没有意义的。最好将控件名称列表保留在字典中并以这种方式引用它们。

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多