transparent controls in winforms
It always bothered me that setting the background of a control to transparent doesn’t actually make the control transparent. I always assumed that because that didn’t work, the workaround had to be messy and difficult. After a little bit of searching today, I came across this awesome code from Tobias Hertkorn on his T# blog. It turns out the solution is a pretty elegant and I not sure why it .net team didn’t make it a property that was easy to set.
Here is his code (C#):
public class TransparentPanel : Panel{
protected override CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return cp;
}
}
protected override void OnPaintBackground(PaintEventArgs e) {
//base.OnPaintBackground(e);
}
}
Here is the VB version of it:
Public Class TransparentPanel
Inherits Panel
Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
Get
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = cp.ExStyle Or &H20 'WS_EX_TRANSPARENT
Return cp
End Get
End Property
Protected Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
'MyBase.OnPaintBackground(e)
End Sub
End Class
The 20 hex comes from the WINUSER.H and there are a few more properties that ExStyle affects. Also, if you plan to have content under the transparent control that is changing often, you will need to add some kind of means of refreshing the transparent controls such as a timer that calls refresh().