3

I draw my contents on a form inside OnPaint event with e.graphics.DrawLine(), etc... . So far I was drawing according to form size (resizing my elements) but now I'd like draw as big as I want, and if I draw outside the visible area (the place where object will be drawn is decided at runtime dynamically), I want user to use scroll bars in order to see parts of whole content which I draw.

I have enabled AutoScrolling but I don't know how it may help me when I don't have any controls on that form.

How can I do it?

Hayri Uğur Koltuk
  • 2,970
  • 4
  • 31
  • 60

2 Answers2

8

Simply set the AutoScrollMinSize property to the size you want. The scrollbar(s) automatically appear when the form's ClientSize is smaller than this value. You'll also need to offset what you draw according to the scroll position, like this:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.AutoScroll = true;
        this.AutoScrollMinSize = new Size(3000, 1000);
        this.ResizeRedraw = true;
    }
    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
        e.Graphics.DrawLine(Pens.Black, 0, 0, 3000, 1000);
        base.OnPaint(e);
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • How can i do this: form size is by default 3000 x 1000 but when I draw something out of this region, scrollbars are visible and I can scroll to the shape which I've drawn out there (lets say at 3500x1200)? – Hayri Uğur Koltuk Jan 05 '12 at 09:51
  • i could not make myself clear, it's my mistake. I meant "...user can scroll to the shape which is drawn out there". Anyway as you told, this is another question and I've found out that something similar (not exactly the same) is already asked and the answer solves my problem: http://stackoverflow.com/questions/2657753/gdi-problem-encountered-in-drawing-multiples-rectangles-on-the-form thanks for help. – Hayri Uğur Koltuk Jan 05 '12 at 14:41
  • Thanks Mr. HansPassant, you have solved my old flickering problem when scrolling by `e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);`, Thanks alot. – Reza Ebrahimi Dec 30 '13 at 07:16
1

First you should set AutoScroll = true; of that Form where you're drawing ,than the best way is to draw things into a Panel and Re-size the Panel to fit the Content drawled inside ,than the Form will Automatically Show it's Scroll Bar's.

Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89