我刚好有个例子,应该能满足你的要求。
function FindExistingForm(FFormName: string): TForm;
var
i: integer;
begin
Result := nil;
try
if FFormName = '' then raise Exception.Create('需要类名!');
with Application do
for i := 0 to ComponentCount - 1 do
if Components.ClassName = ('T' + FFormName) then begin
Result := TForm(Components);
Break;
end;
except
on E: Exception do
ShowMessage(E.Message)
else raise;
end;
end;
function CreateForm(FFormName: string
AOwner: TComponent): TForm;
type
TFormClass = class of TForm;
var
AFormClass: TFormClass;
begin
Result := nil;
try
if FFormName = '' then raise Exception.Create('需要类名!');
AFormClass := TFormClass(FindClass('T' + FFormName));
Result := AFormClass.Create(AOwner);
except
on E: Exception do
ShowMessage(E.Message)
else raise;
end;
end;
procedure OtherFormComponentClick(FFormName: string
FComponentName: string
AOwner: TComponent);
var
AForm :TForm;
AComponent :TComponent;
begin
AForm:= FindExistingForm(FFormName);
if AForm=nil then
begin
AForm:=CreateForm(FFormName, AOwner);
AForm.Show;
end;
AComponent:=AForm.FindComponent(FComponentName);
if AComponent<>nil then TButton(AComponent).Click;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
OtherFormComponentClick('Form2', 'MyButton', Self);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
i: integer;
AComponent :TComponent;
begin
with Application do
for i := 0 to ComponentCount - 1 do
begin
AComponent:=TForm(Components).FindComponent('MyButton');
if AComponent<>nil then TButton(AComponent).Click;
end;
end;
procedure TForm1.MyButtonClick(Sender: TObject);
begin
application.MessageBox('TForm1.MyButtonClick','提示');
end;
form2要自注册。
例:
initialization
RegisterClass(TForm2);