How to discover owner from object in Delphi?

5k views Asked by At

I would like to create a procedure that returns me the name of the form where the object is allocated. For example:

I have a TPanel and within TPanel one TButton. I'll pass as a parameter to the function name of TButton and want the function to return me the name of formuário where is this button.

How do?

LE:

function TForm1.DoSomething(Obj: TComponent): String; 
var AClass : String; I : Integer; 
begin 
 AClass := TComponent(Obj).Owner.ClassName; 
 if (AClass = 'TForm') then 
  Result := TComponent(Obj).Name 
else 
 Result := TComponent(Obj).Owner.Name; 
end; 

procedure TForm1.Button1Click(Sender: TObject); 
begin 
 NomeForm := DoSomething(Button3); 
 ShowMessage(NomeForm); 
end; 

procedure TForm1.Button4Click(Sender: TObject); 
begin 
 NomeForm := DoSomething(Form1); 
 ShowMessage(NomeForm); 
end; 
2

There are 2 answers

0
AlexSC On

It seems to me that the procedure GetParentForm declared in Forms unit does what you want. Take a look at

http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Forms_GetParentForm.html

0
Confundir On

Here's a simple example in the same condition you mentioned. A button on a panel, returns the name of the form. the function ReturnForm, will run recursively until finding the form

function TForm22.ReturnForm(aParent: TWinControl): TWinControl;
begin
  Result:= nil;
  if aParent <> nil then
  begin
    if aParent.Parent <> nil then
      Result:= ReturnForm(aParent.Parent)
    else
      Result:= aParent;
  end;
end;

procedure TForm22.Button1Click(Sender: TObject);
begin
  Showmessage(ReturnForm(Button1).Name);
end;

Careful with translations from Portuguese to English:)