Click here to Skip to main content
Click here to Skip to main content

Custom Button Control with Gradient Colors and Extra Image (VB.NET)

, 11 Jan 2013
Rate this:
Please Sign up or sign in to vote.
This is a simple to use custom button control, but with a lot of visual design options.

Introduction

The CButton is a simple custom button control written in VB.NET. Sorry I didn't realize the "C" prefix was a language specific thing when I started. It is just short for Custom Button. I won't let it happen again. This is a great alternative to the plain Microsoft button.

Here is a list of the primary features:

  1. Change the Shape of the button
  2. Adjust the corners of a round rectangle
  3. Solid and Multi color Fills
  4. Text shadow and margin
  5. Adjustable rollover and click color change with simulated click movement
  6. Normal button image and/or additional sideimage

I improved design time editing in Version 1.2 by adding UITypeEditors and ControlDesigners. See UITypeEditorsDemo[^] for a detailed explanation. This enabled me to combine some properties into one single property, or improve on others.

For example:

  • ButtonColorA, ButtonColorB, and ButtonColorC were combined into ColorFillBlend allowing unlimited Color blend instead of being limited to only three colors
  • ButtonColorCenterPoint, and ButtonColorCenterPtOffset were combined into FocalPoints
  • CornerRadius became an expandable property Corners allowing each corner to be adjusted separately

Background

Here is another example of needing (well, let's be honest, a plain button would work, so I wanted) a better looking and visually versatile button. There are a lot of great button controls already, but not with all the features I was looking for. Basically, I created the properties I was looking for, and then took over the OnPaint to draw it the way I wanted.

Control Properties

Here is a list of the primary properties:

  • Shape

    What shape the button is (Rectangle, Ellipse, Triangle)

  • ColorFillBlend

    Colors to use in gradient blend fills

  • BorderColor, BorderShow

    Show the border in a different color

  • FillType

    What color gradient type to use (Solid, Linear, or Path)

  • FocalPoints

    CenterPoint and FocusScales for Path Gradient Type Fills

  • Corners

    Radius for each corner arc

  • DimFactorHover, DimFactorClick

    Number to adjust the buttons color during mouse rollover and click

  • TextShadow, TextShadowShow

    Show or not show the shadow of the text and in what color

  • TextMargin

    Push the text away from the inside edge of the button

  • TextSmoothingMode

    Set the TextRenderingHint of the Graphics Object for better looking text

  • SideImage

    Add an extra image that can be placed outside the button surface

  • Padding

    Offset the edges of the ButtonArea from the edge of the Control

Using the Code

Once you get the CButton designed the way you want, there isn't really any complicated code. Just use it like a normal button.

Because the Click event fires if you click anywhere on the control, I added two new Events; the ClickButtonArea event in Version 1.1 to fire only when the mouse clicks inside the button part of the control, and the SideImageClicked event in Version 2.0.

    'Add a new Click event for only when the ButtonArea or SideImage is Clicked
    Public Event ClickButtonArea(ByVal Sender As Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs)
    Public Event SideImageClicked(ByVal Sender As Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs)


Private Sub CButton_MouseUp(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
    If MouseDrawState = eMouseDrawState.Down _
        Then RaiseEvent ClickButtonArea(Me, New EventArgs)
    MouseDrawState = eMouseDrawState.Up
    Me.Invalidate(ButtonArea)
End Sub

Points of Interest

The control is just a process of layering the parts together in the right positions. There are four main areas to track. The control area, button area, text area, and image area. The button area is reduced from the control area by the control padding values. The text area is reduced from the button area by the text margin values and the image area. The image area is based on the image size. The items are placed into these areas based on their layout options.

Protected Overrides Sub _
    OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias
    e.Graphics.TextRenderingHint = _TextSmoothingMode

    'Gray the Text and Border Colors if Disabled
    Dim bColor, tColor, tsColor As Color
    If Me.Enabled Then
        bColor = _BorderColor
        tColor = Me.ForeColor
        tsColor = _TextShadow
    Else
        bColor = GrayTheColor(_BorderColor)
        tColor = GrayTheColor(Me.ForeColor)
        tsColor = GrayTheColor(_TextShadow)
    End If

    Dim MyPen As New Pen(bColor)
    MyPen.Alignment = PenAlignment.Inset

    'Shrink the Area so the Border draws correctly, _
    'then trim off the Padding to get the button surface area
    ButtonArea = AdjustRect(New RectangleF(0, 0, _
        Me.Size.Width - 1, Me.Size.Height - 1), Me.Padding)

    'Create the ButtonArea Path
    Dim gp As GraphicsPath = GetPath()

    If Me.BackgroundImage Is Nothing Then

        'Color the ButtonArea with the right Brush
        Select Case Me.FillType
            Case eFillType.Solid
                Using br As Brush = New SolidBrush(GetFill)
                    e.Graphics.FillPath(br, gp)
                End Using

            Case eFillType.GradientPath
                Using br As PathGradientBrush = New PathGradientBrush(gp)
                    Dim cb As New ColorBlend
                    cb.Colors = GetFillBlend()
                    cb.Positions = Me.ColorFillBlend.iPoint

                    br.FocusScales = FocalPoints.FocusScales
                    br.CenterPoint = New PointF( _
                        Me.Width * FocalPoints.CenterPoint.X, _
                        Me.Height * FocalPoints.CenterPoint.Y)
                    br.InterpolationColors = cb

                    e.Graphics.FillPath(br, gp)
                End Using

            Case eFillType.GradientLinear
                Using br As LinearGradientBrush = New LinearGradientBrush( _
                  ButtonArea, Color.White, Color.White, FillTypeLinear)
                    Dim cb As New ColorBlend
                    cb.Colors = GetFillBlend()
                    cb.Positions = Me.ColorFillBlend.iPoint

                    br.InterpolationColors = cb

                    e.Graphics.FillPath(br, gp)
                End Using

        End Select
    End If

    If BorderShow Then
        e.Graphics.DrawPath(MyPen, gp)
    End If
    gp.Dispose()

    Dim ipt As PointF = ImageLocation(GetStringFormat(Me.SideImageAlign), _
        Me.Size, Me.SideImageSize)

    rectSideImage = New Rectangle(CInt(ipt.X), CInt(ipt.Y), _
        Me.SideImageSize.Width, Me.SideImageSize.Height)

    'Put the SideImage behind the Text
    If SideImageBehindText AndAlso Me.SideImage IsNot Nothing Then
        If Me.Enabled Then
            e.Graphics.DrawImage(Me.SideImage, ipt.X, ipt.Y, _
                Me.SideImageSize.Width, Me.SideImageSize.Height)
        Else
            ControlPaint.DrawImageDisabled(e.Graphics, _
            New Bitmap(Me.SideImage, Me.SideImageSize.Width, _
            Me.SideImageSize.Height), _
            CInt(ipt.X), CInt(ipt.Y), Me.BackColor)
        End If
    End If

    'Layout the Text and Image on the button surface
    SetImageAndText(e.Graphics)

    If Not Me.Image Is Nothing Then
        If Me.Enabled Then
            e.Graphics.DrawImage(Me.Image, Imagept.X, Imagept.Y, _
                Me.ImageSize.Width, Me.ImageSize.Height)
        Else
            ControlPaint.DrawImageDisabled(e.Graphics, Me.Image, _
                CInt(Imagept.X), CInt(Imagept.Y), Me.BackColor)
        End If
    End If

    'Draw the Text and Shadow
    If TextShadowShow Then
        TextArea.Offset(1, 1)
        e.Graphics.DrawString(Me.Text, Me.Font, _
            New SolidBrush(tsColor), TextArea, GetStringFormat(Me.TextAlign))
        TextArea.Offset(-1, -1)
    End If
    e.Graphics.DrawString(Me.Text, Me.Font, _
        New SolidBrush(tColor), TextArea, GetStringFormat(Me.TextAlign))

    'Put the SideImage in front of the Text
    If Not SideImageBehindText AndAlso Not Me.SideImage Is Nothing Then
        If Me.Enabled Then
            e.Graphics.DrawImage(Me.SideImage, ipt.X, ipt.Y, _
                Me.SideImageSize.Width, Me.SideImageSize.Height)
        Else
            ControlPaint.DrawImageDisabled(e.Graphics, _
            New Bitmap(Me.SideImage, _
            Me.SideImageSize.Width, Me.SideImageSize.Height), _
            CInt(ipt.X), CInt(ipt.Y), Me.BackColor)
        End If
    End If

    MyPen.Dispose()
End Sub

To Gray the colors when the control is disabled, I used two methods:

To Gray a single color, I used this Function:

Function GrayTheColor(ByVal GrayColor As Color) As Color
   Dim gray As Integer = _
    CInt(GrayColor.R * 0.3 + GrayColor.G * 0.59 + GrayColor.B * 0.11)
   Return Color.FromArgb(GrayColor.A, gray, gray, gray)
End Function

To Gray an Image, I originally used this Function:

Private Function EnableDisableImage(ByVal img As Image) As Bitmap
    If Me.Enabled Then Return img
    Dim bm As Bitmap = New Bitmap(img.Width, img.Height)
    Dim g As Graphics = Graphics.FromImage(bm)
    Dim cm As ColorMatrix = New ColorMatrix(New Single()() _
         {New Single() {0.5, 0.5, 0.5, 0, 0}, _
        New Single() {0.5, 0.5, 0.5, 0, 0}, _
        New Single() {0.5, 0.5, 0.5, 0, 0}, _
        New Single() {0, 0, 0, 1, 0}, _
        New Single() {0, 0, 0, 0, 1}})

    Dim ia As ImageAttributes = New ImageAttributes()
    ia.SetColorMatrix(cm)
    g.DrawImage(img, New Rectangle(0, 0, img.Width, img.Height), 0, 0, _
        img.Width, img.Height, GraphicsUnit.Pixel, ia)
    g.Dispose()
    Return bm

End Function

In Version 2.0, I switched to the ControlPaint function because I thought the image was better looking.

ControlPaint.DrawImageDisabled(e.Graphics, Me.Image, _
    CInt(Imagept.X), CInt(Imagept.Y), Me.BackColor)

FocalPoints

New in Version 1.5, when the FillType is GradientPath a small square and circle selection will appear on the control. Drag the circle around to move the CenterPoint, and drag the square to move the FocusScales. Check out the UITypeEditorsDemo link above to see an explanation of this feature.

TypeConverter for ColorFillBlend

New in Version 2.0, a TypeConverter for the ColorFillBlend can convert a String representation of the blend to a cBlendItems to allow more precise tweaking and to easily copy a blend from one cButton to another.

History

  • Version 1.0 - May 2008
  • Version 1.1 - July 2008
    • Updated "Clickable Region" and added a ClickButtonArea event
  • Version 1.2 - September 2008
    • Updated Properties to use UITypeEditors and ControlDesigner
    • Added Triangular Buttons
  • Version 1.3 - September 2008
    • Button Area Click Fix. The button did not click when the mouse was moving
  • Version 1.4 - October 2008
    • Added Enable/Disable Feature
  • Version 1.5 - December 2008
    • Fixed the FocalPoints and Corners properties to immediately refresh the control when the child properties are changed in the PropertyGrid
    • Removed FocalPoints Modal UITypeEditor and added direct adjustment of the points on the design surface
  • Version 1.6 - January 2009
    • Added Mnemonic Keys based on NfErNo's suggestion.
  • Version 1.7 - April 2009
    • Added SendMessage for click through non button area
  • Version 1.8 - November 2009
    • Added Key events based on getholdofphil's suggestion
    • Fixed focus problem
  • Version 1.9 - July 2010
    • Switched the Disable Image routine to ControlPaint method
    • Added TextSmoothingMode property
    • Added SideImageClicked Event
    • Changed the ClickButtonArea EventArgs to MouseEventArgs to pass the mouse button easier
  • Version 2.0 - December 2011
    • Added IButtonControl Interface for PerformClick and DialogResult 
    • Added BlendItemsConverter to the cBlendItem Type 
  • Version 2.0 - January 2013
    • Added Visual Studio 2012 version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

SSDiver2112
Software Developer
United States United States
I first got hooked on programing with the TI994A. After it finally lost all support I reluctantly moved to the Apple IIe. Thank You BeagleBros for getting me through. I wrote programs for my Scuba buisness during this time. Currently I am a Database manager and software developer. I started with VBA and VB6 and now having fun with VB.NET

Comments and Discussions

 
QuestionPossible Bug Pinmemberlightpulp28-Jun-14 8:33 
AnswerRe: Possible Bug PinpremiumSSDiver211225-Aug-14 4:30 
GeneralMy vote of 1 PinmemberRixterz1239-Jun-14 7:34 
GeneralRe: My vote of 1 PinpremiumSSDiver21129-Jun-14 10:05 
QuestionMessage Automatically Removed PinmemberMember 108363642-Jun-14 3:15 
GeneralMessage Automatically Removed PinmemberMember 1083636421-May-14 22:36 
Questionchange border width Pinmemberarungpalakka29-Jan-14 21:45 
AnswerRe: change border width PinmemberSSDiver21121-Feb-14 18:28 
GeneralRe: change border width Pinmemberarungpalakka3-Feb-14 2:37 
GeneralاHi PinmemberMember 1052165713-Jan-14 9:43 
QuestionBackground trandsparancy for Eclipse/Triangle button shapes.. PinmemberGary Miyakawa11-Jan-14 5:38 
AnswerRe: Background trandsparancy for Eclipse/Triangle button shapes.. PinmemberSSDiver211213-Jan-14 11:32 
GeneralRe: Background trandsparancy for Eclipse/Triangle button shapes.. PinmemberGary Miyakawa13-Jan-14 13:06 
QuestionInterested PinmemberNebojsaPopovic7-Jan-14 0:11 
Questionhow to add control to other projects Pinmembermscirocco16-Nov-13 16:29 
GeneralRe: how to add control to other projects... Solved for VS2012 Pinmembermscirocco17-Nov-13 17:21 
QuestionCButton and VS2008 PinmemberAndrea Galvanin20-Oct-13 23:34 
GeneralCButton - the best Pinmemberennex12-Oct-13 13:49 
QuestionCButton error Pinmembert_nedelchev4-Oct-13 4:26 
QuestionHow to use in the C# ?? Pinmemberjbkim2u30-Sep-13 22:37 
QuestionDimTheColor Pinmembert_nedelchev17-Sep-13 4:40 
QuestionError when building or debugging with VS2010 PinmemberMember 102552335-Sep-13 8:57 
AnswerRe: Error when building or debugging with VS2010 PinmemberSSDiver21125-Sep-13 9:43 
GeneralRe: Error when building or debugging with VS2010 PinmemberMember 102552335-Sep-13 9:47 
QuestionEnable or Disable PinmemberPinaki Mukherji4-Sep-13 2:07 
QuestionVery New to programming - Please help if you can PinmemberMember 1004076221-Aug-13 4:05 
QuestionImage Behaviour When Disabled PinmemberMember 1021853319-Aug-13 15:50 
Questionerror CButtonLib.CButton Pinmemberquimicosa21-Apr-13 17:16 
QuestionNewb with a problem after adding Cbuttons PinmemberMember 993531123-Mar-13 17:30 
GeneralCan popup design time editor be invoked at runtime? PinmemberJonHB13-Mar-13 12:27 
GeneralRe: Can popup design time editor be invoked at runtime? PinmemberSSDiver211218-Mar-13 15:56 
QuestionColorFillBlend.iColor Issue Pinmemberpitoloko15-Jan-13 2:20 
AnswerRe: ColorFillBlend.iColor Issue PinmemberSSDiver211215-Jan-13 13:24 
GeneralRe: ColorFillBlend.iColor Issue Pinmemberpitoloko15-Jan-13 22:20 
GeneralRe: ColorFillBlend.iColor Issue PinmemberSSDiver211216-Jan-13 3:10 
QuestionPerformClick() does nothing Pinmemberpitoloko12-Jan-13 6:28 
AnswerRe: PerformClick() does nothing PinmemberSSDiver211212-Jan-13 7:39 
GeneralRe: PerformClick() does nothing Pinmemberpitoloko12-Jan-13 7:54 
GeneralRe: PerformClick() does nothing PinmemberSSDiver211212-Jan-13 8:36 
GeneralRe: PerformClick() does nothing Pinmemberpitoloko12-Jan-13 8:40 
QuestionObject of type 'System.Int32' cannot be converted to type 'System.Int16' PinmemberMember 396415919-Nov-12 23:13 
AnswerRe: Object of type 'System.Int32' cannot be converted to type 'System.Int16' Pinmemberpitoloko11-Jan-13 5:32 
GeneralRe: Object of type 'System.Int32' cannot be converted to type 'System.Int16' PinmemberSSDiver211211-Jan-13 8:48 
GeneralRe: Object of type 'System.Int32' cannot be converted to type 'System.Int16' Pinmemberpitoloko12-Jan-13 6:26 
QuestionUse in C# Pinmemberjojotjo5-Nov-12 6:59 
QuestionError on: Global.CButton.My.MySettings [modified] Pinmemberdherrmann25-Oct-12 10:07 
GeneralMy vote of 5 Pinmemberpetervanekeren17-Oct-12 2:07 
Great usercontrol! Looks great and has a lot of options.
QuestionButton not curved ? Pinmemberclaudetom0114-Oct-12 10:30 
SuggestionRe: Button not curved ? Pinmemberclaudetom0116-Oct-12 8:54 
GeneralMy vote of 5 PinmemberTamok5-Oct-12 14:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 11 Jan 2013
Article Copyright 2008 by SSDiver2112
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid