- Create a class that inherits from
Panel
. - Set the
ControlStyle.Opaque
for control in constructor usingSetStyle
.
If true, the control is drawn opaque and the background is not
painted.
- Override
CreateParams
and setWS_EX_TRANSPARENT
style for it.
Specifies that a window created with this style is to be transparent.
That is, any windows that are beneath the window are not obscured by
the window. A window created with this style receives WM_PAINT
messages only after all sibling windows beneath it have been updated.
- Create an
Opacity
property that accepts values from 0 to 100 that will be used as alpha channel of background. - Override
OnPaint
and fill the background using an alpha enabledBrush
that is created fromBackGroundColor
andOpacity
.
Complete Code
public class ExtendedPanel : Panel
{
private const int WS_EX_TRANSPARENT = 0x20;
public ExtendedPanel()
{
SetStyle(ControlStyles.Opaque, true);
}
private int opacity = 50;
[DefaultValue(50)]
public int Opacity
{
get
{
return this.opacity;
}
set
{
if (value < 0 || value > 100)
throw new ArgumentException("value must be between 0 and 100");
this.opacity = value;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
using (var brush = new SolidBrush(Color.FromArgb(this.opacity * 255 / 100, this.BackColor)))
{
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
base.OnPaint(e);
}
}
Screenshot