views:

317

answers:

1

This is kinda....a two part question. The first one is much more important than the second one, both of these are in the same project, and in vb.net.

How can I constrain the bounds of a rectangle object, which is controlled by a mouse, so it cannot be drawn outside a PictureBox? It is kindof a standard lasso control, the user can click and drag and it will draw a box from the initial click point to the mouse's current location. The starting point is at (rectX,rectY), and the box is drawn to the bottom right using rectDimX and rectDimY (to set the width and height) to see how much of a change has occurred with the mouse. Basically, its what you get with a click and drag on a Windows desktop. The issue here is that the rectangle is able to be drawn outside the PictureBox it is being drawn on, and the next part of the code attempts to reference this location, and then fails with an OutOfMemory exception. This leads me to my second question:

How can I make the rectangle draw in more than the fourth quadrant, which is only positive numbers? If it goes anywhere else, it does not show the rectangle, though it does still have the correct values. I know i could code this four times based on starting location and mouse location, but that would be a huge hassle and a rewrite of the whole rectangle code.

Is there an easy solution for either of these? The first one is a much bigger hassle, as it will be very time consuming if there is no easy way.

Thanks for the help!

+1  A: 

For the first part of your question, even if the user drags the mouse beyond the edge of your picture box, you don't have to use those coordinates for your drawing routine. Simply do something like

If (DrawingPoint.X > PictureBox.Right)
   DrawingPoint.X = PictureBox.Right // Right-hand limit of picture box
End If

And similar for the Y direction.

As for the negative numbers while drawing, you want to translate screen coordinates to client area coordinates. Have a look at ScreenToClient and ClientToScreen.

Eric J.
It is negative numbers which are the issue, the rectangle, when to the left or above the mouse, has a negative height or width. Of course, I could just set it to the absolute value and shift it over....which I may actually do. Wow, i wonder why I did not think of that before lol!
Cyclone
Generally you want to "translate" the origin of your mouse to the origin of your drawing window. Edited my answer above with info about this (since I understand that part now)
Eric J.
Hmm, I am still confused about this...can you give a syntax example for translating the drawing window to the X and Y of the PictureBox?
Cyclone
Success! I have solved, entirely, the second part of my issue, it will now ALWAYS show the lasso regardless of quadrant. It took a bit of thinking, but I solved that. Now, how can i fix the other part?
Cyclone