delphi

How to get actual background color of TWinControl?


On a form, I have several controls placed on each other, for example:

TForm/TPageControl/TTabSheet/TGroupBox...

I'm trying to obtain the actual background color of the top-most control. How can I do this bearing in mind that each control can have different value of its ParentColor property and exact number of (nested) controls is unknown at design time?

I tried Windows API GetBkColor function, but it does not return the actual color.

I tried to write the recursive function for that but it does not work because the ParentColor property of TWinControl is protected:

  function GetColor(C: TWinControl): TColor;
  begin
    if C.ParentColor {compiling error is here} and Assigned(C.Parent) then
    begin
      Result := GetColor(C.Parent)
    end
    else
      //Result := C.Color; //compiling error is here...
      Result := C.Brush.Color;
  end;

The things probably get worse because of ParentBackround property which can have different value for each control...

So, how to get the actual background color of the top-most TWinControl?

UPDATE: It seems, just querying Brush.Color does the trick (thanks to Sherlock70). Will it always work or, maybe I need to add additional checks?


Solution

  • TWinControl has no exposed Color property. Look in to the Brush property, Brush.Color to be exact. For (not so much) further reading consult: https://docwiki.embarcadero.com/Libraries/Athens/en/Vcl.Controls.TWinControl.Brush.

    As to the question if this will always work...that is up to the components creator/manager. Also this might not be the right way in FMX.