delphipascal

How can I access a Delphi control from outside the form’s unit?


I’m trying to call the Enabled property of a Timer from a procedure defined like this:

procedure Slide(Form: TForm; Show: Boolean);

and not with a fixed form name (like: Form2.Timer…).

After putting the form’s unit in the uses list, this works:

Form2.Timer1.Enabled := True;

but the following is not working:

Form.Timer1.Enabled := True;

(where Form is the form passed as parameter to the procedure).

How do you get access to the Timer component in my form?


Solution

  • You cannot access the Timer from your procedure because your parameter is a TForm, and TForm does not have a Timer1 member. You have to adjust your procedure like this:

    uses
      Unit2; //unit with your form
    
    procedure Slide(Form: TForm2; Show: Boolean); //change TForm2 to the classname you use
    begin
      Form.Timer1.Enabled := True;
    end;
    

    Edit:

    If you want to pass any form, you can try this:

    procedure Slide(Form: TForm; const aTimerName: string; Show: Boolean);
    var
      lComponent: TComponent;
    begin
      lComponent := Form.FindComponent(aTimerName);
      if Assigned(lComponent) and (lComponent is TTimer) then
        TTimer(lComponent).Enabled := True;
    end;
    

    Call like this from a button on your form:

    procedure TForm2.Button1Click(Sender: TObject);
    begin
      Slide(Self, 'Timer1', False);
    end;
    

    Or you let your Form inherit an interface with methods to turn on the timer. It's a little bit more complicated though.