2

Not sure on what to make title please edit if needed. I have a procedure

procedure TFZone1Mod7.ChangeText(sender: TObject);
var
  ShapeOrderNo: integer;
  FoundComponent: TComponent;
begin
  if TryStrToInt(copy(TShape(Sender).Name,6,MaxInt),ShapeOrderNo) then
    begin
      FoundComponent := FindComponent('label'+inttostr(ShapeOrderNo+12));
      if (FoundComponent is TLabel) then
            Label25.Caption := TLabel(FoundComponent).Caption
      else
          showmessage('not found');
    end;
  showmessage(TShape(sender).Name);

end;

so i call the procedure on a Shape1MouseEnter. So i would think (Self) would send shape1 but it dont it sends the form(TFZone1Mod7) How i can get it to send the shape? here is how i am calling it.

procedure TFZone1Mod7.Shape1MouseEnter(Sender: TObject);
begin
    changetext(self);
end;
Glen Morse
  • 2,437
  • 8
  • 51
  • 102
  • 2
    You mention `Self` in your question, but there is no `Self` in your code. Please show how `Self` is involved. – Jeroen Wiert Pluimers Oct 23 '12 at 07:14
  • sorry pasted thw wrong snip at the end. now fixed. – Glen Morse Oct 23 '12 at 07:16
  • Your final code should read `ChangeText(Sender)` as `Sender` is the `TShape` for which the `OnMouseEnter` event fired the `Shape1MouseEnter` method. You might even consider `ChangeText(Sender as TShape)` just in case you hook the `Shape1MouseEnter` method to an `OnMouseEnter` of a control that is not a `TShape` – Jeroen Wiert Pluimers Oct 23 '12 at 09:31

1 Answers1

4

Inside this method

procedure TFZone1Mod7.Shape1MouseEnter

Self is an object of type TFZone1Mod7. And that's your form. Remember that Self refers to the instance associated with the active method. And in your code, the class is a form and so the instance, Self, is always a form instance.

To know what Self is, look at the type that follows the procedure or function keyword. The Self instance is an instance of that type.

In your situation, if you want to pass the shape you can pass either Shape1, or to be more general, Sender. The latter allows you to share one event handler between multiple shapes.

This sort of mistake highlights why you should use checked casts with the as operator. When you make a mistake, you will get informed of it immediately and in a helpful way. Your unchecked casts just lead to hard to understand cryptic errors.

So I'd probably be inclined to declare ChangeText as receiving a parameter of type TShape. And then calling it like this:

ChangeText(Sender as TShape);

And this allows you to remove the casts from ChangeText and confine them just to the event handlers which by necessity only have a TObject instance, Sender, available.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490