formsdelphimethodsproceduredynamicobject

Access object on another form with the form as a variable


I'm writing a program in Delphi which includes creating the same dynamic object on multiple forms (never simultaneously), and then a procedure in another unit writes certain text to it.

How the object (TMemo) is created:

memHulp := TMemo.Create(frmHome);
with memHulp do
begin
  Parent := frmHome;
  Top := 208;
  Left := 88;
  Height := 98;
  Width := 209;
  ReadOnly := True;
end;

The properties aren't that important, it's just to show the creation of the object and how it is referred to.

Now, I need to read certain text into the memo from a text file, which there is no problem with, but the problem comes when there are different forms involved that all use that same self-defined procedure.

It's easy to say frmHome.memHulp.Lines.Add() in this particular case, but when I need it to display the text on the memo named exactly the same in all cases, but on a different form, I'm having some trouble.

The frmHome part needs to be a variable. So I tried this:

var 
  Form: TForm;
begin
  Form := Application.FindComponent('frmHome') as TForm;
end;

That doesn't warn me or give an error, but as soon as I try to say Form.memHulp.Lines.Add(), it does not work, and I understand that it probably doesn't have any properties for Form, but how do I make it look at the correct place? I need to be able to tell the program to look on whichever form name I pass as a parameter into the FindComponent() part.

If this is completely not possible, please suggest other solutions to achieve the same.


Solution

  • Form.memHulp doesn't work because Form is a plain vanilla TForm pointer, and TForm doesn't have a memHulp member. You could use Form.FindComponent('memHulp') instead, since you are assigning the TForm object as the Memo's Owner, but that would require you to assign a Name to the Memo, eg:

    memHulp := TMemo.Create(frmHome);
    with memHulp do
    begin
      Parent := frmHome;
      Name := 'memHulp';
      ...
    end;
    

    Alternatively, since you say you are creating only 1 Memo object at a time, you could simply make memHulp be a global variable in some unit's interface section, and then you would have direct access to it without having to hunt for it.