James R. answered 07/27/19
Developer and Entrepreneur selling C# based commercial software.
I have used a couple of ways to do things like this.
(1) First of all, I assume you are creating a Rectangle object and you have a list of the created rectangles, as an array of some sort, or better still, you have been adding the rectangles to the picture box, using the Controls.Add() method. in this case, I have used two ways:
- When you get a click in the picture box, loop thru its controls, and for every rectangle found, use the rectangle.Contains(Point) method to detect whether of not the rectangle has been drawn. Exit the loop as soon as you get a hit.
- Or, immediately after drawing each rectangle, create a "shadow" picture box, with transparent color, and no border, and with exactly the same bounds as the created rectangle. Create a click handler for the shadow picture boxes. You can use the same method for them all. Set the rectangle's tag to the shadow picture box. Now, whenever you rotate a rectangle, just grab the tag and cast as a picture box, and reset the bounds to be the same as the rectangle you just rotated. On the other hand, when you get a click inside the main picture box, if the point is inside one of the rectangles, the click handler for the corresponding shadow picture box will have been fired, and you can then do whatever you want. This technique might be faster than looping, but you have to remember to clean up those shadow boxes at the appropriate time.
You might even create an object class that contains both the rectangle and the shadow picture box and then manipulate them together (add to the main picture box controls, rotate, click event, etc.)
(2) If you are not using rectangle objects, but manually drawing rectangles on an image surface that serves as the background image of the picture box, then you can still use the technique explained in (1) by simply creating a shadow picture box for each drawn rectangle. Keep a dictionary of your list of points and the corresponding shadow picture box, so that when you rotate the rectangle, you can also change the bounds of the picture box. Then you can use either the looping method, or click handler as above to determine whether and which rectangle was hit on a click.
(3) Do you really need to use a Rectangle? If not, use embedded picture boxes inside the main one instead. Then the click handler takes care of the rest.