Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to parent form in Delphi

I'm writing my own component which inherited from TButton. I need to make some manipulation with parent form where my new component will be placed.

So, How to access to parent form from my own component code?

Code example (MyComponentCode.pas):

ButtonParent.Canvas.Pen.Color := RGB(255,255,255); // where "ButtonParent" have to be a parent form

Help me to resolve this problem. Thank you.

like image 595
Alexander Seredenko Avatar asked Apr 15 '16 18:04

Alexander Seredenko


2 Answers

To access the parent TForm that your component resides on, even if your component is actually on another container control (like a TPanel or TFrame), use the GetParentForm() function in the Vcl.Forms unit:

uses
  ..., Forms;

var
  Form: TCustomForm;
begin
  Form := GetParentForm(Self);
  //...
end;
like image 140
Remy Lebeau Avatar answered Oct 04 '22 04:10

Remy Lebeau


The parent is the control that holds the control.
If you drop a control on a panel, then the parent will be the panel.

The owner of a control will usually be the form that holds it, but this is not always the case. If you work with Frames, than the frame will own the controls inside it.

The way to get to the form that owns your control is to keep going up the tree until you find a real form.

You can call VCL.Forms.GetParentForm, which looks like this:

function GetParentForm(Control: TControl; TopForm: Boolean = True): TCustomForm;
begin
  while (TopForm or not (Control is TCustomForm)) and (Control.Parent <> nil) do
    Control := Control.Parent;
  if Control is TCustomForm then
    Result := TCustomForm(Control) else
    Result := nil;
end; 

Or if you want to get there through the owner you can do:

function GetOwningForm(Control: TComponent): TForm;
var
  LOwner: TComponent;
begin
  LOwner:= Control.Owner;
  while Assigned(LOwner) and not(LOwner is TCustomForm) do begin
    LOwner:= LOwner.Owner;
  end; {while}
  Result:= LOwner;
end;

It's important to grok the difference between the parent and the owner, see:
http://delphi.about.com/od/objectpascalide/a/owner_parent.htm

Of course you can use the same trick with the parent property. If you go up the tree long enough (almost) every control1 will have the form as its parent.

1) some controls have no parent.

like image 36
Johan Avatar answered Oct 04 '22 05:10

Johan