1

I'm working on delphi components. I've been trying to access a customized component's designated parent control's onClick event. By designate, users can designate the component's parent control by using object inspector as a property. parent controls can be any of control components on the same form. However, because all parent controls I've made are subclasses of TControl and onClick event of TControl is protected, I can not access parent control's onclick event. practically, a customized component is like a sub-component positioned right next to a parent control, so whenever, a user clicks a customized component, I wanted parent control's click event will occur, if click event exists.

when I run this code, typecasting exception occurs.

 procedure TSubCom.SetParentControl(const Value : TControl);
 var
 parentContLeft : Integer;             //parent control's left + width
 parentContTop : Integer;              //parent control's top
 begin
 FParentControl := Value;
 parentContLeft := FParentControl.Left + FParentControl.Width;
 parentContTop := FParentControl.Top;
 Left := parentContLeft - (Width div 2);
 Top := parentContTop - (Height div 2);
 Repaint;
 end;

//TSubCom's onClick event is linked with its parent control's onClick event
procedure TSubCom.Click;
var
Parent: wrapClass;
begin
inherited;
if(FParentControl <> nil) then
begin
  ShowMessage(FPArentControl.Name);
  Parent := FParentControl as wrapClass;
  ShowMessage('1');
  if Assigned(Parent.OnClick) then
  begin
    Parent.OnClick(Self);
  end;
 //    FParentControl as FParentControl.ClassType;
 //    if(FParentControl.OnClick <> nil) then
 //     FParentControl.OnClick;
end;
end;
eesther
  • 57
  • 1
  • 7
  • 1
    I think you're trying to use an interposer class here. If so, you can't use the `as` operator, but have to directly typecast (`Parent := WrapClass(FParentControl);`) instead. – Ken White Nov 26 '14 at 13:55

1 Answers1

4

Declare a class for accessing protected members, typecast the Parent to this class, and do not use the OnClick event, instead use Click.

type
  TControlAccess = class(TControl);

procedure TSubCom.Click;
begin
  inherited Click;
  if ParentControl <> nil then
    TControlAccess(ParentControl).Click;
end;
NGLN
  • 43,011
  • 8
  • 105
  • 200
  • 4
    Also known as a *cracker class*, and traditionally with 'Crack' or 'Hack' in the name, eg `TControlCracker`: http://www.delphigroups.info/2/08/295084.html and http://hallvards.blogspot.com/2004/06/hack-5-access-to-private-fields.html and http://stackoverflow.com/questions/1423411/delphi-how-to-know-when-a-tedit-changes-size – David Nov 26 '14 at 14:46