Dragging Square

lothos12345

Well-known member
Joined
May 2, 2002
Messages
294
Location
Texas
I have a visual basic.net application I need the user to be able to click at one point on a form and drag, once they let off the click it will draw a square. However I am not sure how to accomplish this. Any programming examples would greatly be appreciated.
 
In MouseDown store the point where the user clicked (e.X and e.Y) into a point structure (lets say, P1)
In MouseUp store the point where the user released (e.X and e.Y) into another point structure (lets say, P2)

Create a rectangle, not a square, from these two points by calculating a left, top, right, and bottom value for the rectangle.
The left is the minimum of the X coordinate of the points P1 and P2
The top is the minimum of the Y coordinate of P1 and P2
Right is the maximum of the X coordinates
and Bottom is the maximum of the Y coordinates.
You should now have a rectangle (lets say, R1)

To draw the square, you have your choice of getting access to a graphics object.

Dim GFX As Graphics

GFX = Me.CreateGraphics()
gets a graphics object that draws onto the form.

Use this graphics object to draw a rectangle.
GFX.DrawRectangle(Pens.Black, R1)
:)
 
User See

Thanks for the help that worked great, but I also need the user to see the rectangle has they are dragging to create it. How can this be accomplished? Any help given is greatly appreiciated.
 
You do the same thing as you did above, except that your P2 is the coordinates of the points created from MouseMove when the button is pressed.

Then, to draw the rectangle, youll want to clear the area, otherwise youll get a slimetrail rectangle. If you have a background, draw it before you draw the rectangle.
:)
 
Back
Top