Gradient Background on .NET Windows Forms or Controls

Posted by VIJI Wednesday, February 17, 2010

The following few lines of code adds cool gradient background to the .NET windows forms or controls.

1. Imports System.Drawing.Drawing2D
2. Add the following in New() function

Public Sub New()

' This call is required by the Windows Form Designer.
InitializeComponent()

' Add any initialization after the InitializeComponent() call.


Me.SetStyle(System.Windows.Forms.ControlStyles.DoubleBuffer, True)
Me.SetStyle(System.Windows.Forms.ControlStyles.AllPaintingInWmPaint, True)
Me.SetStyle(System.Windows.Forms.ControlStyles.ResizeRedraw, True)
Me.SetStyle(System.Windows.Forms.ControlStyles.UserPaint, True)

End Sub
3. Add the following in Paint() function of Form

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
'Fill Panel with gradient colors Red and Blue
Dim rect As New System.Drawing.Rectangle(0, 0, e.ClipRectangle.Width, e.ClipRectangle.Height)

Dim g As Graphics = e.Graphics

Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), System.Drawing.Color.Red, Color.Blue)
g.FillRectangle(gradientBrush, rect)

End Sub


1. We can do the same thing for all Form Controls by adding the above three lines in the Paint Event of the controls (E.x Panel )

The following Code snippet explains how to paint the panel with gradient background.
Private Sub Panel1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint
'Fill Panel with gradient colors white and green
Dim rect As New System.Drawing.Rectangle(0, 0, e.ClipRectangle.Width, e.ClipRectangle.Height)

Dim g As Graphics = e.Graphics

Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), System.Drawing.Color.White, Color.Green)
g.FillRectangle(gradientBrush, rect)

End Sub

3 Responses to Gradient Background on .NET Windows Forms or Controls

  1. ghastie Says:
  2. This worked really well for me. I am beginner so while it may seem obvious how can perform this gradient vertically or from the center out/in etc.

     
  3. Anonymous Says:
  4. nice

     
  5. Anonymous Says:
  6. Even though this was posted back in 2010... it is realy helpful for me today (06.09.2014). So, many thanks!!!

     

Post a Comment