Navigation

How to create components with a transparent background

To do that kind of stuff right, create a new control derived for example
from TGroupbox, and override its CreateParams method
like this:

protected{in control declaration}procedureCreateParams(varparams:TCreateParams);override;procedureTTransparentGroupbox.CreateParams(varparams:TCreateParams);begininheritedCreateParams(params);params.ExStyle:=params.ExStyleorWS_EX_TRANSPARENT;end;{Add a handler for the WM_ERASEBKGND message}procedureWMEraseBkGnd(varmsg:TWMEraseBkGnd);messageWM_ERASEBKGND;procedureTTransparentGroupbox.WMEraseBkGnd(varmsg:TWMEraseBkGnd);beginSetBkMode(msg.DC,TRANSPARENT);msg.result:=1;end;

That is the basic frame for a TWinControl descendent. For a
TGraphicsControl you would drop the CreateParams
(since only WinControls have that method) and override the create
constructor. After calling the inherited constructor you modify the
ControlStyle of the control:

In this demo we'll create a new transparent group box
(TGroupBoxEx) and, to demonstrate a transparent
TGraphicControls, a new transparent label
(TLabelEx). I know that TLabel has a
Transparent property, but this is just a proof of concept
example!

Start a new Delphi VCL application and create OnPaint and
OnCreate event handlers for the main form. Name the
form "Form1" and save the form unit as
Unit1.pas.

We've painted a candy stripe background on the form to help
demonstrate transparency. You'll see the normal label and group box
use the form's default colour as a background, while the new
components are truly transparent (except for the label of the group
box) and the candy stripes show through.

Demo by Peter Johnson

Transparency actually works better for TGraphicControls than for
TWinControls. The latter have problems if the control is moved or
the background needs to change. Delphi container controls (like form or
panel) are always created with the WS_CLIPCHILDREN style, which
automatically excludes the area under child controls from updates, so the
background will not be updated if required. Removing the
WS_CLIPCHILDREN style from a controls parent is possible with: