1
votes

I make the code by using Delphi.
When I press the button, it create a new MDI child form.
So, the program has multiple MDI child form, and I want to access the component(for example, timer) of each child form in the MainForm.
MainForm is fsMDIForm, and ChildForm is fsMDIChild.

Here is the code I tried. But it doesn't work because TChildForm and TForm is not compatible.

procedure TMainForm.Start1Click(Sender: TObject);
var   
i : Integer;
begin
  for i := MainForm.MDIChildCount-1 to 0 do
  begin
    ChildForm := MainForm.MDIChildren[i];   //Incompatible types -> Can't Run
    ChildForm.Timer1.Enabled := True;
  end;
end;

unit MDIChildForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ToolWin, ActnMan, ActnCtrls, ComCtrls, Buttons,
  ExtCtrls;

type
  TChildForm = class(TForm)
    ToolBar1: TToolBar;
    ListView1: TListView;
    ToolButton1: TToolButton;
    Splitter1: TSplitter;
    Memo1: TMemo;
    ToolButton2: TToolButton;
    Timer1: TTimer;
    procedure FormCreate(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  ChildForm: TChildForm;
  value1: Integer = 1;

implementation

{$R *.dfm}

procedure TChildForm.FormCreate(Sender: TObject);
begin
  {
    itm := ListView1.Items.Add;
    itm.Caption := 'item ' + IntToStr(value1);
    itm.SubItems.Add('subItem1 ' + IntToStr(value1));
    itm.SubItems.Add('subItem2 ' + IntToStr(value1));
  }
  Timer1.Enabled := False;
  {
    ChildForm.Caption := 'ChildForm' + IntToStr(value1);
    Inc(value1);
  }
end;
procedure TChildForm.ToolButton1Click(Sender: TObject);
begin
  ToolButton1.Show;
  value1 := value1 + 10;
end;

procedure TChildForm.ToolButton2Click(Sender: TObject);
begin
  //ListView1.Items.Item[0] := 'Index';
end;

procedure TChildForm.Timer1Timer(Sender: TObject);
var
  itm : TListItem;
  i : Integer;
begin
  for i:= value1 to value1+10 do
  begin
    itm := ListView1.Items.Add;
    itm.Caption := 'item ' + IntToStr(i);
  end;
  value1 := i;
end;

end.

How I can access the component in child form?
1
How is ChildForm declared? Is MainForm a fsMDIForm. Your question lacks required details. Please edit and provide a minimal reproducible exampleTom Brunberg
I added more information about my code. Sorry to what I have to upload, so I uploaded full code about ChildForm. Please review my question.jayjay

1 Answers

3
votes

You need to use a cast like this:

procedure TMainForm.Start1Click(Sender: TObject);
var   
  i : Integer;
begin
  for i := MainForm.MDIChildCount-1 downto 0 do
    (MainForm.MDIChildren[i] as TChildForm).Timer1.Enabled := True;
end;

Also note that I used downto in the for loop since you want to traverse the child list backward.