Search code examples
c#winformsscrollgraphicspicturebox

Make a picturebox scroll dynamically


I've seen some answers here but I didn't find something that is suitable to my problem.

I have a picture box which I am drawing on it dynamiclly some rectangles (like so: Change color of graphic rectangle dynamically).

Now, if the I draw a lot of rectangles, then the picture box isn't big enough, I don't see all the rects... so I need to make the picture box scrollable.

How is it possible?

Note: I don't have a Panel, just a PictureBox that I am filling dynamically through the code.


Solution

  • You should place the PictureBox inside a Panel, with AutoScroll=true.

    Then you can simply make the PictureBox larger as needed, maybe even right where the DrawRectangles are created..:

    public DrawRectangle(Rectangle r, Color c, float w, Control ct)
    {
        color = c;
        width = w;
        rect = r;
        surface = ct;
    
        if ((r.Right > surface.Width)  ||  (r.Bottom > surface.Height))
        {
            surface.Size = new Size(Math.Max(surface.Width, r.Right),
                                    Math.Max(surface.Height, r.Bottom)) ;
        }
    }