Make a scrolled window in C#

[example]

Making a scrolled window is really easy, at least if you’ve seen how to do it before. If you haven’t seen it, you can spend a lot of time building your own scrolled window out of PictureBox, VerticalScrollBar, and HorizontalScrollBar controls.

Suppose you have something such as a large picture that doesn’t fit nicely on a form. You might like to display it in a scrolled window so the user can pan around and see different parts of the picture. You can accomplish that by using a nested pair of PictureBox controls and some scroll bars, but there’s a much easier way.

Put the picture in a PictureBox and set its SizeMode property to AutoSize so it resizes itself to show the whole picture. Then put the PictureBox inside a Panel control and set that control’s AutoScroll property to true. Now the Panel control automatically displays scroll bars and arrange its contents when the user scrolls. You don’t need to write any code and only need to set a single property: AutoScroll.

If the Panel control is anchored so it resizes when the form resizes, the control will even display and hide either or both of its scroll bars as needed. If the user makes the form big enough to display everything, the scroll bars disappear. If the user make the form small, the scroll bars appear and function appropriately.

The Panel control doesn’t need to hold a single control as it does in this example. You can place any number of controls inside it and it will still let the user scroll to see them all. (If you have a lot of controls, it’s sometimes easier work with them in the form designer if you place them in a single container such as a PictureBox and then place the PictureBox inside the Panel control, but that’s not a requirement.)


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in miscellany, user interface and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.