Pointers Lazarus从TForm.Components获取指针

Pointers Lazarus从TForm.Components获取指针,pointers,pascal,lazarus,freepascal,Pointers,Pascal,Lazarus,Freepascal,如何获取TForm.Components[x]的指针。这是我的程序的简化版本,用于理解问题的背景。我只需要以这种方式获得它(使用组件列表)。 非常感谢 unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type TLabel1=class(TLabel) public My

如何获取TForm.Components[x]的指针。这是我的程序的简化版本,用于理解问题的背景。我只需要以这种方式获得它(使用组件列表)。 非常感谢

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;

type
  TLabel1=class(TLabel)
    public
      MyColor:TColor;
    end;

  TLabel2=class(TLabel)
    public
      myLabel1:^TLabel1;
      procedure paint;override;
      procedure Click;override;
  end;

{ TForm1 }

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  end;

var
  Form1: TForm1;
  l1:TLabel1;
  l2:TLabel2;

implementation

{$R *.lfm}

procedure TLabel2.paint;
begin
  canvas.brush.color:=clRed;
  canvas.Rectangle(0,0,width,height);
  if mylabel1<>nil then
    canvas.TextOut(0,0,myLabel1^.Caption)
  else
    canvas.TextOut(0,0,Caption);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  l1:=TLabel1.Create(self);
  l1.Parent:=self;
  l1.Left:=24;
  l1.Top:=24;
  l1.Caption:='I am L1';

  l2:=TLabel2.Create(self);
  l2.Parent:=self;
  l2.Left:=24;
  l2.Top:=64;
  l2.Caption:='I am L2';
  l2.myLabel1:=nil;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  freeandnil(l1);
  freeandnil(l2);
end;

procedure TLabel2.Click;
begin
  //here is where I need to understand how to get the pointer
  myLabel1:=@TLabel1(form1.Components[0]);
  invalidate;
end;

end.
单元1;
{$mode objfpc}{$H+}
接口
使用
类、SysUtils、FileUtil、窗体、控件、图形、对话框、stdctrl;
类型
TLabel 1=类别(TLabel)
公众的
霉色:TColor;
结束;
TLabel2=类别(TLabel)
公众的
myLabel1:^TLabel1;
程序漆;推翻
程序点击;推翻
结束;
{TForm1}
TForm1=类(TForm)
过程表单创建(发送方:ToObject);
销毁程序表(发送方:TObject);
结束;
变量
表1:TForm1;
l1:TLabel1;
l2:TLabel2;
实施
{$R*.lfm}
程序2.油漆;
开始
canvas.brush.color:=clRed;
画布。矩形(0,0,宽度,高度);
如果mylabel1nil,则
canvas.TextOut(0,0,myLabel1^.Caption)
其他的
canvas.TextOut(0,0,标题);
结束;
过程TForm1.FormCreate(发送方:TObject);
开始
l1:=TLabel1.创建(自我);
l1.父母:=自己;
l1.左:=24;
l1.顶部:=24;
l1.说明:='我是l1';
l2:=TLabel2.创建(自我);
l2.父母:=自我;
l2.左:=24;
l2.顶部:=64;
l2.说明:=‘我是l2’;
l2.myLabel1:=nil;
结束;
程序TForm1.FormDestroy(发送方:ToObject);
开始
freeandnil(l1);
freeandnil(l2);
结束;
程序2.点击;
开始
//这里是我需要了解如何获取指针的地方
myLabel1:=@TLabel1(form1.Components[0]);
使无效
结束;
结束。

myLabel1:=TLabel(Form1.Components[0])对对象的引用已经是指针。(顺便说一句,您对
TLabel2.myLabel1的定义不正确。与其使用
myLabel:^TLabel1
,不如使用
myLabel:TLabel1;`。)好的,简单更好;谢谢@KenWhite。无需在表单的OnDestroy中明确销毁l1和l2,因为l1和l2是以表单所有者(“self”)的身份创建的,因此表单将负责销毁。