如何测试当前应用程序中是否存在某个组件,例如如果您创建了一个名为radiogroup1的动态单选组,如何检查是否已经有一个名为radiogroup1的组件?
如何测试当前应用程序中是否存在某个组件,例如如果您创建了一个名为radiogroup1的动态单选组,如何检查是否已经有一个名为radiogroup1的组件?
首先,您需要列出应用程序中所有的表单。
之后,您需要使用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;
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;
type
TFrameClass=class of TFrame;
procedure TForm1.LoadFrame(CurrentFrame: TFrameClass; Name:String);
var
Reference:TFrameClass;
Instance:TFrame;
begin
Instance:=TFrame(FindComponent(Name));
if (Instance=nil) then
begin
Reference:=TFrameClass(CurrentFrame);
Instance:=Reference.Create(Self);
Instance.Align := alClient;
Instance.Parent := ClientPanel;
end
else
begin
Instance.BringToFront;
end;
end;
procedure TForm1.scGPCharGlyphButton4Click(Sender: TObject);
var FrameInternalDistribution:TFrameInternalDistribution;
begin
LoadFrame(TFrameInternalDistribution, 'FrameInternalDistribution');
end;
procedure TForm1.scGPCharGlyphButton2Click(Sender: TObject);
var
FrameInboxDistribution:TFrameInboxDistribution;
begin
LoadFrame(TFrameInboxDistribution, 'FrameInboxDistribution');
end;
FindComponent
都可能是您所提出的问题的答案,但是对于您的潜在问题,谁知道呢。 - David HeffernanFindComponent()
的作用域是组件级别的,因为它是TComponent
的一个方法。只有当该组件恰好是TForm
时,它才是窗体级别的。 - Remy Lebeau