Most of the info in this post can be found between the following two links:
http://stackoverflow.com/questions/2065162/filled-rubber-band-in-winforms-application
https://msdn.microsoft.com/en-us/library/3t7htc9c(v=vs.110).aspx
Drawing a bounding box over an image to select a region took me longer to figure out than I expected. Here’s a brief bare-bones example demonstrating how to do it.
To follow along, pop a PictureBox form inside of a form, and set a background image. Make sure you can run the program and see this work as expected.
What’s next is pretty straightforward. First you need to create callbacks for the mouse down and mouse up events captured by the PictureBox. We’ll need to set a value in the main form class to indicate that the mouse is currently down.
The way this is going to work is that on the MouseDown event, the location of the mouse is going to be stored, and we’ll also store the current point of the mouse as it moves around (while the mouse button is still held down). Using those two points, we’ll draw a box.
Next let’s update the MouseDown callback to include capturing the initial mouse down point, and also add a MouseMove callback to update the current point.
Now it’s time to do the actual drawing of the box. This is done by making a callback for the Paint event that the PictureBox receives whenever it’s “dirty”. Inside that callback is where the rectangle drawing happens. We’ll trigger this Paint event manually by calling the Invalidate() method on the PictureBox in the MouseDown, MouseUp, and MouseMove callbacks, too.
Here it is all together.
Here is a Gist: https://gist.github.com/anonymous/6788f9f3095ed40ec06b4f5795c2d1c2
And here’s the final result. You’ll have to imagine the mouse cursor on the bottom-right of that red box since printscreen doesn’t capture it.
I usually try to put the code inline with the post, but I got frustrated fighting the WordPress code formatting! The context for this post is that I made a toy Mandelbrot fractal viewer and I wanted to draw a box around an area I wanted to zoom into.