By default, the containers and user controls in .NET have opaque background. There is no way to set a transparent background. This is OK in most cases, but in cases where you want your user control to show through, you are stuck. In this article we will see how we can set a transparent background for our container controls and UserControls.
Build a UserControl with transparent background.
1. Add the following code to your UserControl
2. The code above will work for most situations. But in cases, where you would change the background of the control this usercontrol is on (or overlaps), you will observe that it doesn’t refresh properly. In such cases, call the Refresh method immediately after setting the background image.
That’s it. Enjoy!
How it works
We have overridden 3 default members of our custom control. I’ll explain the significance of each override:
1. CreateParams: The CreateParams class has all the information needed for the control being created. Here we are interested in the CreateParams.ExStyle which defines extended attributes of the control.
Read more about it here: http://msdn.microsoft.com/en-us/libr…ateparams.aspx
2. OnPaintBackground: Next we override the OnPaintBackground method which is essentially responsible for painting the control background whenever there is a need for it. But we don’t want to paint it with its background color or image. We override the default behavior and keep it empty so that it does nothing.
3. Refresh: The default refresh will paint the control and all its child control. We don’t want it to be called. So we override it and let the Parent (i.e. the form or container in which our control is in) paint itself. The Parent will paint the UserControl background with whatever is actually in the background.