Your solution is really a "hack" which is absolutely not needed.
The real solution is a combination of properties of the child object and a parent panel, which should be of the the panel type derived from
System.Windows.Forms.ScrollableControl
, such as "regular"
System.Windows.Forms.Panel
.
First of all, this is not true that you cannot use
Dock
with chilren. You can use either
Dock
or
Anchor
, and I would advise to prefer docking, as anchoring is more manual in development and support and more likely causes flicker. So, I will show the code sample with docking. I will take care only about horizontal dimension:
namespace AutoScrollApplication {
using System.Windows.Forms;
public class AutoScrollForm : Form {
internal AutoScrollForm() {
Panel pad = new Panel();
pad.Dock = DockStyle.Fill;
this.Controls.Add(pad);
TextBox textBox = new TextBox();
textBox.Dock = DockStyle.Top;
pad.Controls.Add(textBox);
pad.AutoScroll = true;
pad.AutoScrollMinSize = new System.Drawing.Size(300, 0);
}
[System.STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new AutoScrollForm());
}
}
}
For the purpose of the demo, I avoided using the designer and put all the application in just one file. If you build it, it will show the exact effect you wanted.
That's it.
[EDIT]
Please see my warning about the inappropriate
immediate constant 300 I put just for illustration of the technique. You could do better by using the current size of the window. For this purpose, use, for example:
pad.AutoScrollMinSize =
new System.Drawing.Size(this.ClientRectangle.Width, 0);
In this case, the scrolling will be set exactly on the boundary between two modes: when a window is first shown, the scroll bar is not visible. From this point, if you make your form wider, the child
TextBox
will grow in width, if you make if narrower, the scroll bar appears.
Isn't that nice?
Good luck,
—SA