3

I want to be able to limit where a component is created.

Like for instance, TMyChild could be a TButton, and TMyParent could be a TPanel, and when I drop MyChild onto some other component I want MyChild to check if it is being created in a TMyParent/TPanel or not.

If it is, then fine lets do it, if it is NOT created in a TMyParent/TPanel then cancel the TMyChild creation and show a message that says something like: "Sorry, MyChild needs to be created in MyParent!".

Thank you!

menjaraz
  • 7,551
  • 4
  • 41
  • 81
xaid
  • 740
  • 6
  • 18

1 Answers1

9

You must override the Controls.TControl.SetParent method.

  TMyChild = class(TControl)
  protected
    procedure SetParent(AParent: TWinControl); override;
  end;


procedure TMyChild.SetParent(AParent: TWinControl);
begin
  if (AParent <> nil) then
  begin
    if not (AParent is TMyParent) then
      raise Exception.CreateFmt('Sorry, MyChild needs to be created in MyParent!', [ClassName]);
  end;
  inherited;
end;
RRUZ
  • 134,889
  • 20
  • 356
  • 483
  • 2
    This does not _cancel_ or _prevent_ placement. Maybe call inherited afterwards? – NGLN Feb 28 '12 at 08:35
  • I cant see any cancelation in the code neither. maybe Destroy; would be a good cancelation? – xaid Feb 28 '12 at 20:15
  • @xaid, when the exception is raised the parent property is no set. So the child component is not placed in the Parent component. – RRUZ Feb 28 '12 at 20:21