For a lot of applications we might want to draw a rectangle on a picturebox to allow the user to select a region. This is actually much easier than one might think. We are going to take advantage of the picturebox's drawmode property. If we set drawmode to "vbinvert" anything drawn on the picturebox will invert the pixels behind it. Basically, if we draw a rectangle once we invert the pixels in the picturebox, when we draw the same rectangle again, they invert again and the rectangle disappears without a trace. Cool huh?
We are going to store a few variables so that we can remeber our key locations. The mousedownx and mousedowny variables store the location of our mousedown click. This is always one corner of our rectangle.
The lastx and lasty variables store the location of our last rectangle. Remember, when we draw this rectangle a second time it goes away thanks to the magic of "vbinvert".
And the drawlastbox variable is a flag. When the flag is true we already have a rectangle drawn so we need to draw it again (to erase it). When the flag is false, there is no rectangle to erase.
So lets give it a try: start a new project, add a picturebox (Picture1), and paste the following code. Viola! You can draw rectangles to your heart's content. A simiar technique can be used to draw lines, circles, and a whole host of stuff. Heck, we could come up with a simple drawing app in an hour or two. Adobe Photoshop, watch out!!!
Have fun, Ryan
If you found this helpful, please let me know at "ralarsen AT gmail.com"
Dim mousedownx As Single 'stores the coord of the mousedown event Dim mousedowny As Single 'stores the coord of the mousedown event Dim lastx As Single 'stores the coord of the last mouse position Dim lasty As Single 'stores the coord of the last mouse position Dim drawlastbox As Boolean
Private Sub Picture1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = vbLeftButton Then mousedownx = X lastx = X mousedowny = Y lasty = Y drawlastbox = False End If End Sub
Private Sub Picture1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = vbLeftButton Then Picture1.DrawMode = vbinvert If drawlastbox Then Picture1.Line (mousedownx, mousedowny)-(lastx, lasty), , B End If Picture1.Line (mousedownx, mousedowny)-(X, Y), , B lastx = X lasty = Y drawlastbox = True End If End Sub