在设计时获取表单的组件

时间:2013-05-05 12:18:40

标签: forms delphi components design-time

我创建了一个组件,当在设计时双击它时,它会创建另一个表单。代码如下:

function TMyComponentTest1.Execute: Boolean;
var
  Form: TMyComponentTest1Form;
begin
  try
    Form := TMyComponentTest1Form.Create (nil);
    Form.ShowModal;
  finally
    Form.Free;
  end;
end;

在这个新形式中,我必须获得主要设计形式的组件,但我不能这样做,有没有人知道我如何能够实现这一目标? 我也尝试使用“self”进行创建,但是当我双击它时,delphi会崩溃......

1 个答案:

答案 0 :(得分:0)

以下是我认为可以使用的一些未经测试的代码。让我们将您的组件称为TMyComponent。您必须在TMyComponent的designtime包中创建TMyComponentTest1Form,作为组件编辑器和/或属性编辑器的一部分。

然后,尝试像这样创建TMyComponentTest1Form:

function TMyComponentTest1.Execute: Boolean;
var
  aForm: TMyComponentTest1Form;
  OwnerForm: TForm;
  aMyComponent: TMyComponent;
begin
  {OwnerForm is your main design form}
  OwnerForm := nil;

  {Get your component on the main design form}
  aMyComponent := TMyComponent(GetComponent(0))

  {Make sure your component's owner is a TForm}
  if (aMyComponent.Owner is TForm) then
    OwnerForm := TForm(aMyComponent.Owner);

  {You problem may be solved by making component form owner the Application}
  aForm := TMyComponentTest1Form.Create(Application);
  try
    {
    Now you should be able iterate the components owned by OwnerForm
    right here. If you do not want to do it here, add a TForm property 
    to your component and assign OwnerForm to it.
    }
    aForm.ShowModal;
  finally
    aForm.Free;
  end;
end;