Accesing to nonpublished events, methods and properties  

Send By: Radikal (Q3 Team)
Web :
Date: 06/06/20

Tip accessed 685 times


For example:

We want add an OnClick event handler to a TTrackBar.
The TTrackbar does not have OnClick event, so we will have to do something to have him.
We can create a component derived from the TTrackBar, publish its OnClick event, save it, install it in Delphi and soon to use it... but it is a quite uncomfortable process you do not think this?

The hierarchy of classes of which tTrackBar descends is the following one:


as we can see, the TTrackBar descends from the TWinControl class, which descends from a TControl that YES, it has an OnClick event handler.
This what means?, that somewhere, the creator of the TrackBar component decided not to incoporporate this event to the component.
Surely it would think (and with reason) that with the OnChange event already it would be enough.

How we will be able then to use the event.
Good, we can do a 'hack' class and be able to access thus to all the properties, events and methods of the TrackBar.

For example, lets go to create an event handler for the OnClick of TrackBar1:

The declaration inthe private part of the form's declaration:

   procedure Trackbar1Click(Sender: TObject);

and its implementation:


 {$R *.dfm}

 procedure TForm1.Trackbar1Click(Sender: TObject);
   ShowMessage('TrackBar1 OnClick fired!');

Now, we would have to assign it, in runtime, for example in the OnCreate of the form, with something like:

 Trackbar1.OnClick :=Trackbar1Click;

but..., we see that we do not have available the handler of OnClick events, since in the definition of the TrackBar it is not defined in the Published part...

In order to avoid this limitation, we will use a 'hack' class.
We will declare in the type part of the form:

   THackClass = class(TTrackBar);

   TForm1 = class(TForm)

and then, we will be able to assign the OnClick of our TrackBar1 with something like this:

  THackClass(Trackbar1).OnClick :=Trackbar1Click;