Creating a .NET Transparent Panel

In the overabundance of .NET controls, one can probably forgive Microsoft for not having enough Properties for certain controls. On the other hand, some Properties are quite redundant, but that is just my opinion. I have always wanted an Opacity property for most .NET controls. It is probably an impractical thought, but it would have saved me a ton of hours manipulating and improving existing .NET controls.

Yes, you are able to set the Background color of controls to Transparent, but this causes the control to be completely see-through. What if you wanted the control to only be semi-transparent, or what if you wanted to be able to set the control’s opacity?

I’m sure I’m not alone on this.

To make controls semi-transparent, you would need to create a component that inherits from the desired control. This will cause the newly created component to act and look like the control in question. Then, you would have to override the existing control’s properties and methods.

In your project today, you will create a new Panel component, as stated above, add a new property named Opacity to the panel, override its Paint event to compensate for the new opacity settings, and add the semi-transparent parameter to the Panel window object. You can follow along in either C# or VB.NET.

Practical

Create a new Windows Forms project in either C# or VB.NET. Name it anything descriptive. Once the project has been created, add a Component to your project by selecting Project, Add Component. Figure 1 shows a dialog that will be displayed. Provide a nice name for your component.

Add Component
Figure 1: Add Component

Add the necessary namespaces to your component.

C#

using System.ComponentModel;

VB.NET

Imports System.ComponentModel

Ensure that your Panel object inherits from “Panel.”

C#

public partial class Panel_C : Panel

VB.NET

Partial Public Class Panel_VB
   Inherits Panel

Add the Transparent Window setting. You will use this setting once you override the Window’s create parameters.

C#

      private const int WS_EX_TRANSPARENT = 0x20;

VB.NET

      Private Const WS_EX_TRANSPARENT As Integer = &H20

WS_EX_TRANSPARENT specifies that a window created with this style is to be transparent. A full list of all the available Extended Windows Styles can be found here.

Add the Constructors.

C#

      public Panel_C()
      {

         InitializeComponent();

         SetStyle(ControlStyles.Opaque, true);

      }

      public Panel_C(IContainer con)
      {

         con.Add(this);

         InitializeComponent();

      }

VB.NET

      Public Sub New()

         SetStyle(ControlStyles.Opaque, True)

      End Sub

      Public Sub New(con As IContainer)

         con.Add(Me)

      End Sub

Add the Opacity Property.

C#

      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;
         }

      }

VB.NET

      Private iopacity As Integer = 50

      <DefaultValue(50)>
      Public Property Opacity() As Integer

         Get

            Return Me.iopacity

         End Get

         Set

            If Value < 0 OrElse Value > 100 Then

               Throw New ArgumentException("value must be between _
                  0 and 100")

            End If

            Me.iopacity = Value

         End Set

      End Property

You now will be able to choose this property from the Properties Window.

Override CreateParams.

C#

      protected override CreateParams CreateParams
      {

         get
         {

            CreateParams cpar = base.CreateParams;

            cpar.ExStyle = cpar.ExStyle | WS_EX_TRANSPARENT;

            return cpar;

         }

      }

VB.NET

      Protected Overrides ReadOnly Property CreateParams () _
            As CreateParams

         Get
            Dim cpar As CreateParams = MyBase.CreateParams

            cpar.ExStyle = cpar.ExStyle Or WS_EX_TRANSPARENT

            Return cpar

         End Get

      End Property

The CreateParams property gets all the required creation parameters when a control handle is created. Override OnPaint.

C#

      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);
      }

VB.NET

      Protected Overrides Sub OnPaint(e As PaintEventArgs)

         Using brush = New SolidBrush(Color.FromArgb(Me.Opacity _
               * 255 / 100, Me.BackColor))

            e.Graphics.FillRectangle(brush, Me.ClientRectangle)

         End Using

         MyBase.OnPaint(e)

      End Sub

Here, you have created the Panel with the appropriate Opacity setting. Build your project. After you have built your project, you should notice your component in the Toolbox, as shown in Figure 2.

Toolbox
Figure 2: Toolbox

Double-click the component in the toolbox and choose a BackColor. In the next image (see Figure 3), I have added a button, a standard panel, and the newly created component. I have set the Component’s BackColor to 255; 128; 128, and you can clearly see the button underneath it.

Transparent Panel in action
Figure 3: Transparent Panel in action

The source code for this article is available on GitHub.

Conclusion

When in need, create a user component. As you can see, components are very versatile and easy to manipulate. Semi-Transparent controls can be quite useful in a user interface and it is not difficult to create them.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read