Dmitrii Erokhin
Dmitrii Erokhin

Reputation: 1347

Avoid scrolling to the top in TabControl

I have a TabControl with AutoScroll set to true on tabpages. The tabpage contains a RichTextBox, which is bigger in height that the page, so vertical scrollbar appears on a TabPage. If I scroll the page down and then click on the RichTextBox, the page scrolls back to top. Any ideas on how to prevent such behaviour?

UPD: Here is a sample project which can reproduce the issue. The issue occurs when the RichTextBox receives focus. E.g. scroll tabPage1 down, then select tabPage2, return to tabPage1 and click on the RichTextBox.

Upvotes: 0

Views: 2249

Answers (4)

I was experiencing the same problem as you. I solved the problem by setting the AutoScrollMargin property of the tabPanel to 0. This way the page doesn´t scroll to the top.

Upvotes: 0

TheLegendaryCopyCoder
TheLegendaryCopyCoder

Reputation: 1832

The answer while correct was difficult for me to initially understand without seeing the code. Perhaps this helps others.

public class CustomTabPage : System.Windows.Forms.TabPage
{
    protected override System.Drawing.Point ScrollToControl(System.Windows.Forms.Control activeControl)
    {
        //return base.ScrollToControl(activeControl);
        return activeControl.DisplayRectangle.Location;
    }
}

After defining your custom tabpage class, inherit now from this class in your form with your TabControl.

private CustomTabPage tpJobSetup;

Upvotes: 1

Dmitrii Erokhin
Dmitrii Erokhin

Reputation: 1347

Well, after a bit of struggling I've finally found a solution here. All I had to do was to create my own class inherited from TabPage and override the ScrollToControl method, making it return DisplayRectangle.Location.

Upvotes: 2

user2704193
user2704193

Reputation:

This happens due to the fact that once you select the richTextBox and it is "out of sight" it goes to the current position(which in your case is not visible or at the top). If you select the richTextBox first and then scroll you will avoid this. One way you can do this is to Select() the richTextBox on application start.

Add this:

private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.Select();
        }

EDIT:

You can also add the Select() on TabIndexChanged as the behavior will reoccur if you change Tabs.

Upvotes: 1

Related Questions