BLOG.CSHARPHELPER.COM: Make a scrolled window in C#
Make a scrolled window in C#
Over the years, I've posted literally thousands of tips, tricks, and examples on my VB Helper web site. I've posted many examples over such a long time that I don't remember what I've also posted to this site.
This is one of the examples that's so obvious that I didn't realize I hadn't posted it. It's obvious, at least, if you've seen it before. If you haven't seen it, you can spend a lot of time building your own scrolled window out of PictureBoxes, VerticalScrollBars, and HorizontalScrollBars.
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 scroll around to see different parts of the picture. You can accomplish that by using a nested pair of PictureBoxes and some scroll bars, but there's a much easier way.
Put the picture in a PictureBox. Then put the PictureBox inside a Panel control and set its AutoScroll property to true. Now the Panel control will automatically display 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.)
Comments