The following code example shows how horizontal and/or vertical scroll bars are provided automatically as needed when the AutoScroll property is set to true. To run the example, follow these steps:
Create a new Windows Forms application.
Add a Panel to the form.
Add a TextBox to the panel and name it text1.
Move the text box so that the right part extends beyond the right edge of the panel.
You should see only an outline of the part of the text box that is outside the bounds of the panel. If the whole text box is visible, the text box is on the form and not in the panel.
Add a Button to the form.
Add a handler for the Click event of the button.
Add the following example code and call it from the button's Click handler.
When you run the example, you can only see the part of the text box that is inside the boundaries of the panel. When you click the button, you will see a horizontal scroll bar appear that will enable you to see the rest of the text box.
If you position a part of the text box below the bottom of the panel, you will see a vertical scroll bar when you click the button.
The example code checks to see whether the text box is outside the bounds of the panel before it sets the AutoScroll property to true, and before it sets the AutoScrollMargin property. This out-of-bounds check is not required. If AutoScroll is set to true, no scroll bars will appear when the text box is completely within the panel. Also, you can leave the margins at their default settings of 0,0.
Private Sub SetAutoScrollMargins()
' If the text box is outside the panel's bounds,
' turn on auto-scrolling and set the margin.
If (text1.Location.X > panel1.Location.X) Or _
(text1.Location.Y > panel1.Location.Y) Then
panel1.AutoScroll = True
' If the AutoScrollMargin is set to less
' than (5,5), set it to 5,5.
If (panel1.AutoScrollMargin.Width < 5) Or _
(panel1.AutoScrollMargin.Height < 5) Then
panel1.SetAutoScrollMargin(5, 5)
End If
End If
End Sub
private void SetAutoScrollMargins()
{
/* If the text box is outside the panel's bounds,
turn on auto-scrolling and set the margin. */
if (text1.Location.X > panel1.Location.X ||
text1.Location.Y > panel1.Location.Y)
{
panel1.AutoScroll = true;
/* If the AutoScrollMargin is set to less
than (5,5), set it to 5,5. */
if( panel1.AutoScrollMargin.Width < 5 ||
panel1.AutoScrollMargin.Height < 5)
{
panel1.SetAutoScrollMargin(5, 5);
}
}
}
void SetAutoScrollMargins()
{
/* If the text box is outside the panel's bounds,
turn on auto-scrolling and set the margin. */
if ( text1->Location.X > panel1->Location.X || text1->Location.Y > panel1->Location.Y )
{
panel1->AutoScroll = true;
/* If the AutoScrollMargin is set to less
than (5,5), set it to 5,5. */
if ( panel1->AutoScrollMargin.Width < 5 || panel1->AutoScrollMargin.Height < 5 )
{
panel1->SetAutoScrollMargin( 5, 5 );
}
}
}