如何在 Delphi 中访问父表单

How to access to parent form in Delphi

我正在编写自己的组件,该组件继承自 TButton。我需要对放置新组件的父表单进行一些操作。

那么,如何从我自己的组件代码访问父表单?

代码示例(MyComponentCode.pas):

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

帮我解决这个问题。谢谢。

parent是持有控件的控件
如果将控件放在面板上,则 parent 将成为面板。

控件的所有者通常是持有它的窗体,但情况并非总是如此。如果您使用框架,则框架将拥有其中的控件。

到达拥有您的控件的 窗体 的方法是继续沿着树往上走,直到找到真正的窗体。

您可以调用 VCL.Forms.GetParentForm,它看起来像这样:

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; 

或者,如果您想通过所有者到达那里,您可以这样做:

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;

理解 parent 和所有者之间的区别很重要,请参阅:
http://delphi.about.com/od/objectpascalide/a/owner_parent.htm

当然你可以使用与parent 属性相同的技巧。如果你在树上爬得足够长(几乎),每个控件 1 都会有其 parent.

的形式

1)有些控件没有parent.

要访问您的组件所在的父级 TForm,即使您的组件实际上位于另一个容器控件(如 TPanelTFrame),请使用 [= Vcl.Forms单元中的16=]函数:

uses
  ..., Forms;

var
  Form: TCustomForm;
begin
  Form := GetParentForm(Self);
  //...
end;