In VB6 and earlier versions of Visual Basic, drawing rubberband lines is relatively straightforward.
You set the DrawMode to vbInvert and draw a line. To erase the line, you draw it again. The inverse of
the inverse of a pixel is the same as the original pixel so drawing the line twice restores the picture's
original pixels.
For some reason, VB .NET doesn't have invert mode drawing, or any other drawing mode for that matter.
To draw a rubberband line in VB .NET, you need to make a Bitmap object representing the image.
Draw the line on the form. To erase it, copy the stored Bitmap back onto the form.
In the following code, the MouseDown event handler starts the process. It calls subroutine SaveSnapshot and
saves the mouse's position in the variables m_X1, m_Y1, m_X2, and m_Y2.
SaveSnapshot makes a new Bitmap and uses it to create a Graphics object attached to the Bitmap.
When the user moves the mouse, the MouseMove event handler calls subroutine DrawForm to erase any previous line.
It then uses the DrawLine method to draw a line directly on the form. It draws on the form not the saved
Bitmap so the Bitmap doesn't contain that line. The next time the user moves the mouse, the MouseMove event handler
calls DrawForm, which displays the Bitmap without the line.
Subroutine DrawForm simply uses DrawImage to draw the saved Bitmap onto the form.
When the user releases the mouse, the MouseUp event handler uses the saved Bitmap's DrawLine method to draw the
final line on the saved bitmap. It then calls DrawForm to display the bitmap with the new line.
The final piece of code in this program is the Paint event handler. VB .NET has no AutoRedraw property so
if you want the form to display something after it is covered and exposed, you need to handle this explicitly.
This program's Paint event handler calls the DrawForm subroutine to redisplay the saved bitmap.
|