Search code examples
delphifiremonkey

Firemonkey - Object detection


I use Delphi 10.3.3. for Android app.

On the form I have X rectangle objects. I have a question like that: What is the best way to detect who I pressed? (Eg, get its name)


Solution

  • Create an event handler for the OnTap() event.

    In the Object Inspector, assign this event handler to the OnTap event of all the rectangles.

    Using the Sender parameter you can get to the rectangle that triggered the event and find its name. E.g.

    procedure TForm1.Rectangle1Tap(Sender: TObject; const Point: TPointF);
    begin
      ShowMessage((Sender as TControl).Name);
    end;
    

    A sample procedure to create TRectangle instances and assign the event

    procedure TForm1.Button1Click(Sender: TObject);
    var
      i: integer;
      rect: TRectangle;
    begin
      for i := 0 to 5 do
      begin
        rect:= TRectangle.Create(Form1);
        rect.Parent := Form1;
        rect.Position.Point := PointF(10 + i * 75, 10);
        rect.Name := 'Rectangle'+IntToStr(i);
        rect.OnTap := Rectangle1Tap;
      end;
    end;