Title: One Way to Break the VCL's protected barrier
Question: How can I do polymorphic programming when I want to access the color property of my visual control like TEdit, TListBox etc.
Answer:
Some time, I need to access property that are introduced as protected in parent class. A good example for that, is when you want to change the color property that is introduced in TWinControl as a protected property.
To achieve this goal, you can inherit from the class, promote the protected property to public and use the new extension class to type cast all controls that derived from the base class and gain access to the new public property.
In the example below, I took the buggy example contain in the help of delphi4, TScreen.OnActiveControlChange, and used my technique to correct it. Without the type cast, the code could not be compile.
here's the example:
TWinControlEx = class(TWinControl)
public
property Color; //protected in TWinControl
end;
...
...
procedure TForm1.ColorControl(Sender: TObject);
var
I : Integer;
begin
for I:= 0 to ControlCount -1 do
begin
if Controls[I] is TWinControl then
begin
if TWinControl(Controls[I]).Focused then
TWinControlEx(Controls[I]).Color := clRed
else
TWinControlEx(Controls[I]).Color := clWindow;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Screen.OnActiveControlChange := ColorControl;
end;
By the way, there is a reason why the property is protected in TWinControl class. This is because, not all descendents of TWinControl use the color property. Class TButton for example does not. But my experience demonstrate that you can access the property with no side effect even when the property has not been implemented by de descendent class. ex: TWinControlEx(Button1).Color := clRed does not have any effect. But the safe way is to test it.
You can also use the technique with methods etc.
I did not shared this tip with anybody until I saw an article from informant website that state that it is safe to use the technique.
If you want to take a look at the informant article go to www.delphizine.com/features/2000/11/di200011jm_f/di200011jm_f.asp
the article also give some other technique to achieve similar goals.