Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDraw a rubberband rectangle
Keywordsrubberband, rectangle, user drawing
CategoriesGraphics
 
Use a form-level variable to indicate whether the program is drawing the rectangle. In the MouseDown event handler, start drawing in vbInvert mode.

In the MouseMove event handler, if we are drawing then erase the previous rectangle and draw the new one.

In the MouseUp event handler, stop drawing and make the rectangle permanent.

The DrawShape subroutine separates the drawing from the mouse interactions so it is easy to change the rubberband shape.

 
Option Explicit

Private m_Drawing As Boolean
Private m_X1 As Single
Private m_Y1 As Single
Private m_X2 As Single
Private m_Y2 As Single

' Start drawing.
Private Sub picCanvas_MouseDown(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    If Button And vbRightButton Then
        ' It's the right button. Cancel the draw.
        If m_Drawing Then
            ' Erase the previous shape.
            DrawShape

            ' Stop drawing.
            m_Drawing = False
            picCanvas.DrawMode = vbCopyPen
            picCanvas.DrawStyle = vbSolid
        End If
    Else
        ' Start drawing.
        m_Drawing = True
        picCanvas.DrawMode = vbInvert
        picCanvas.DrawStyle = vbDot
        m_X1 = X
        m_Y1 = Y
        m_X2 = X
        m_Y2 = Y

        ' Draw the first shape.
        DrawShape
    End If
End Sub

' Continue drawing.
Private Sub picCanvas_MouseMove(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    ' Do nothing if we're not drawing.
    If Not m_Drawing Then Exit Sub

    ' Erase the previous shape.
    DrawShape

    ' Save the new point.
    m_X2 = X
    m_Y2 = Y

    ' Draw the new shape.
    DrawShape
End Sub

' Finish drawing.
Private Sub picCanvas_MouseUp(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    ' Do nothing if we're not drawing.
    If Not m_Drawing Then Exit Sub

    ' Erase the previous shape.
    DrawShape

    ' Stop drawing.
    m_Drawing = False
    picCanvas.DrawMode = vbCopyPen
    picCanvas.DrawStyle = vbSolid

    ' Save the new point.
    m_X2 = X
    m_Y2 = Y

    ' Make the shape permanant. This might involve saving
    ' coordinates to a database or something. In this case,
    ' it just means redrawing the shape in non-invert mode.
    DrawShape
End Sub

' Draw the shape in the area defined by the points
' (m_X1, m_Y1) and (m_X2, m_Y2).
Private Sub DrawShape()
    picCanvas.Line (m_X1, m_Y1)-(m_X2, m_Y2), , B
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated