Difference between revisions of "Creating Transparent Controls (.NET)"

From HashVB
Jump to: navigation, search
 
m (Reverted edit of Xk2Gie, changed back to last version by Dee)
 
(8 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 +
{{VB.NET}}
 
In today's UI design an odd shaped Control is not a rarity anymore, here is how you can do it in VB.NET.
 
In today's UI design an odd shaped Control is not a rarity anymore, here is how you can do it in VB.NET.
  

Latest revision as of 14:57, 14 July 2007

float
 This article is based on Visual Basic.NET. Find other Visual Basic.NET articles.

In today's UI design an odd shaped Control is not a rarity anymore, here is how you can do it in VB.NET.

Like with any control, you need to decide from what existing class you will inherit, this might be Control, UserControl or any another existing control that allows you to inherit from...

To create an odd shape your Control must by transparent, and you then only paint the parts of interest.

Note that this example does not prevent the user from clicking on the transparent part, if this is a problem you will need to handle it with additional code to not respond to the user when clicked in transparent parts, or to make the Control click-trough on these parts.

The example below just inherits from Control, which is the base class of all Controls in .NET, and it just draws the circle you see in a RadioButton.

If you don't know the ControlPaint class yet take a few minutes to play with it, it has function members to draw all sorts of Control parts.

 Public Class MyTransControl
       Inherits Control
       
       Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
           Get
               ' Make the control transparent.
               Dim MyParams As CreateParams = MyBase.CreateParams()
               MyParams.ExStyle = MyParams.ExStyle Or &H20
               Return MyParams
           End Get
       End Property
       
       Protected Overrides Sub OnPaintBackground(ByVal pevent As System.Windows.Forms.PaintEventArgs)
           ' Do nothing (because we want to be transparent).
       End Sub
       
       Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
       
           ' Do whatever drawing you need here, I just use ControlPaint as an example...
           ControlPaint.DrawRadioButton(e.Graphics, 0, 0, 10, 10, ButtonState.Normal)
       
       End Sub
       
 End Class