How to Add a Gradient Background to a Win Form with VB.NET & VB2005

This article and two downloadable Visual Studio Visual Basic solutions provide code that overrides the Form OnPaint event to create beautiful gradient backgrounds for a Windows Form. Also included is code that optimizes form drawing.

Form With Image and Gradient BackGround

First, the code imports:

Imports System.Drawing.Drawing2D

Next, painting is optimized in the form’s load handler:

 

Private Sub DemoOneForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _

Handles MyBase.Load

 

    ‘ Make this form a MDI child of MainForm.

    Me.MdiParent = My.Forms.MainForm

 

    ‘ Optimize Painting.

    SetStyle(ControlStyles.AllPaintingInWmPaint Or _

                ControlStyles.DoubleBuffer Or _

                ControlStyles.ResizeRedraw Or _

                ControlStyles.UserPaint, _

                True)

End Sub

Finally, the Form’s OnPaint method is overridden to paint the gradient background.

‘ Override the OnPaint event for this form.

Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

    ‘ Declare a variable of type Graphics named formGraphics.

    ‘ Assign the address (reference) of this forms Graphics object

    ‘ to the formGraphics variable.

    Dim formGraphics As Graphics = e.Graphics

    ‘ Declare a variable of type LinearGradientBrush named gradientBrush.

    ‘ Use a LinearGradientBrush constructor to create a new LinearGradientBrush object.

    ‘ Assign the address (reference) of the new object

    ‘ to the gradientBrush variable.

    Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), Color.White, Color.DarkMagenta)

 

    ‘ Here are two more examples that create different gradients.

    ‘ Comment the Dim statement immediately above and uncomment one of these

    ‘ Dim statements to see how varying the two colors changes the gradient result.

    ‘ Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), Color.Chartreuse, Color.SteelBlue)

    ‘ Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), Color.White, Color.SteelBlue)

 

    formGraphics.FillRectangle(gradientBrush, ClientRectangle)

End Sub

~ bởi duriangroup on Tháng Sáu 1, 2007.

 
%d bloggers like this: