Title | Draw a rubberband rectangle with and without double buffering in VB .NET |
Description | This example shows how to draw a rubberband rectangle with and without double buffering in VB .NET. |
Keywords | |
Categories | VB.NET, Graphics |
|
|
When the program's form loads, it increments a variable m_NumForms. If this is the first form, the code calls subroutine UseDoubleBuffer and then creates and displays a second form.
If this is the second form, the code simply sets the form's caption.
|
|
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
m_NumForms += 1
If m_NumForms = 1 Then
' We are the first form.
' Double buffer.
UseDoubleBuffer()
Me.Text = "With Double Buffering"
' Display the second form.
Dim frm As New Form1
frm.Show()
Else
Me.Text = "Without Double Buffering"
End If
End Sub
|
|
Subroutine UseDoubleBuffer sets the form's AllPaintingInWmPaint, UserPaint, and DoubleBuffer styles to True.
|
|
' Enable double buffering.
Private Sub UseDoubleBuffer()
Me.SetStyle( _
ControlStyles.AllPaintingInWmPaint Or _
ControlStyles.UserPaint Or _
ControlStyles.DoubleBuffer, _
True)
Me.UpdateStyles()
End Sub
|
|
The form's Paint event handler draws any rectangles that you have already selected. It then draws the current rubberband rectangle of you are selecting a region.
|
|
Private m_Rectangles() As Rectangle
Private m_NumRectangles As Integer
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles _
MyBase.Paint
' Draw the existing rectangles.
e.Graphics.Clear(Me.BackColor)
If Not (m_Rectangles Is Nothing) Then
e.Graphics.DrawRectangles(Pens.Black, m_Rectangles)
End If
' Draw the new rectangle.
If m_Drawing Then
Dim dashed_pen As New Pen(Color.Blue, 1)
dashed_pen.DashStyle = Drawing2D.DashStyle.Dash
Dim new_rect As New Rectangle( _
Min(m_StartX, m_CurX), _
Min(m_StartY, m_CurY), _
Abs(m_StartX - m_CurX), _
Abs(m_StartY - m_CurY))
e.Graphics.DrawRectangle(dashed_pen, new_rect)
dashed_pen.Dispose()
End If
End Sub
|
|
The form with double buffering automatically builds an internal image of the form as the Paint event handler runs and only displays the result when the drawing is done. That make the new image appear smoothly.
The form without double buffering shows each drawing operation as it is finished and as the system is ready to display the result. That gives a noticeable flicker as you stretch the rubberband rectangle, even when the program is drawing only a few rectangles.
|
|
|
|