Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Win Forms Custom Controls

I have spent the past few days setting up a template for building custom controls, using inheritance.  It took me a while to figure this out, but, with the help of some gurus, I now have a nice template.  Here it is for those interested.  Simply replace the Inherits statement with whatever win form control you want to be your base.  I also built a DefaultProperties class which allows me to set the properties for all controls in one place.  I only have this working for Font so far.  Bits and pieces of this are well documented, it just me a while to put those pieces together...yeah, I am a little slow!

<ToolboxBitmap(GetType(Button))> _
 Public Class myButton
    Inherits System.Windows.Forms.Button

    ' BackColor
    ' Change the default background color here.
    Private Shared Shadows ReadOnly Property DefaultBackColor() _
                 As System.Drawing.Color
        Get
            Return SystemColors.Control
        End Get
    End Property    ' DefaultBackColor

    Public Sub New()
        BackColor = DefaultBackColor
        Font = DefaultFont
    End Sub    ' New

  
    Public Function ShouldSerializeBackColor() As Boolean
        Return Not BackColor.Equals(DefaultBackColor)
    End Function    ' ShouldSerializeBackColor 

    Public Shadows Sub ResetBackColor()
        BackColor = DefaultBackColor
    End Sub    ' ResetBackColor

   
    Public Overrides Property BackColor() As System.Drawing.Color
        Get
            Return MyBase.BackColor
        End Get
        Set(ByVal Value As System.Drawing.Color)
            MyBase.BackColor = Value
        End Set
    End Property    ' BackColor


    ' Font
    ' Change the default background color.
    Private Shared Shadows ReadOnly Property DefaultFont() _
                 As System.Drawing.Font

        Get
           ' Read in the default Font  
            Return DefaultProperties.myFont
        End Get
    End Property    ' DefaultFont

    Public Function ShouldSerializeFont() As Boolean
        Return Not Font.Equals(DefaultFont)
    End Function    ' ShouldSerializeFont

   
    Public Shadows Sub ResetFont()
        Font = DefaultFont
    End Sub    ' ResetFont

    Public Overrides Property Font() As System.Drawing.Font
        Get
            Return MyBase.Font
        End Get
        Set(ByVal Value As System.Drawing.Font)
            MyBase.Font = Value
        End Set
    End Property    ' Font


End Class    ' myClass

-----> DefaultProperties Class

Imports System.Windows.Forms

Public Class DefaultProperties
    Public Shared myFont As Font = New Font("Arial", 8)
End Class

 

 

 

 

 

2 Comments

Comments have been disabled for this content.