Freddy
Freddy

Reputation: 876

Make Panel scrollable

I am working on a simple Windows Forms application which consists of a Panel where I draw graphics with Graphic. Let's say, my panel is now of size 300x300 but the content inside is 500x500. Obviously, I need to add scrollbars to the Panel.

My code so far:

public CircuitControl()
{
    // Initialize empty list of circuit objects
    CircuitObjects = new List<CircuitObject>();

    drawingAreaPanel.AutoScroll = true;
    drawingAreaPanel.VerticalScroll.Enabled = true;
    drawingAreaPanel.VerticalScroll.Visible = true;
    drawingAreaPanel.HorizontalScroll.Enabled = true;

    drawingAreaPanel.MaximumSize = new Size(300, 300);
    drawingAreaPanel.Size = new Size(600, 600);
}

But none of these codes create actually a scroll bar. My question is: Where and how do I set the size of the Panel where I actually drew? I think this is the part which is missing. Thanks.

Upvotes: 1

Views: 1032

Answers (3)

KekuSemau
KekuSemau

Reputation: 6856

A clean and simple approach is to set AutoScrollMinSize. This shows the scrollbars (or just one if you leave the other value at 0).
Now drawing through the graphics object will not be scrolled automatically. This can be easily achieved with a transformation matrix, which is set before painting and translates the drawing by the scroll offset.
A pretty example: (this flickers of course without further optimizations)

private void button1_Click(object sender, EventArgs e)
{
    using(Form frm = new Form())
    {
        Panel pnl = new Panel();
        pnl.Paint += delegate (Object snd, PaintEventArgs e2)  {
            Matrix mtx = new Matrix();
            mtx.Translate(pnl.AutoScrollPosition.X, pnl.AutoScrollPosition.Y);
            e2.Graphics.Transform = mtx;
            e2.Graphics.Clear(Color.Black);
            for(int i=0; i <= 125; i++)
                for(int j=0; j <= 125; j++)
                    using(Brush b = new SolidBrush(Color.FromArgb(255, 255-i*2, j*2, (i*j) % 255)))
                        e2.Graphics.FillRectangle(b, new Rectangle(5+j*20, 5+i*20, 20, 20));
        };
        pnl.AutoScrollMinSize = new Size(126*20+10, 126*20+10);
        pnl.Dock = DockStyle.Fill;
        frm.Controls.Add(pnl);
        frm.Padding = new Padding(25);
        frm.ShowDialog(this);
    }
}

Upvotes: 0

christophos
christophos

Reputation: 90

The scrollbars won't show up until there's actually something in the Panel that you can't see all of.

Try placing a larger control, such as a PictureBox, inside the Panel, and setting the PictureBox's initial size as larger than the Panel.

Upvotes: 2

kaliba
kaliba

Reputation: 230

Just add:

drawingAreaPanel.AutoScroll = true;

And it will be done automatically.

€dit: Don't forget to set the anchors in order to get the scrollbars.

Upvotes: 0

Related Questions