TabControl - Autoscroll doesnt work proper

1.7k views Asked by At

I have following problem, i'm creating a TabControl with a few TabPages, the content within the TabPages are dynamic generated, so I decided to make Autoscroll = true. When I change now on a tab, i first have to press on a textbox or checkbox, that i can scroll, thats really annoying. Would be much better, when the scrollfunction is instantly active, when I change the tab. I tried a few things, with focus, but it doesnt changed anything.

 TabControl tc = new TabControl();
                tc.TabPages.AddRange(new TabPage[]
                {
                new TabPage("Noten 2015"),
                new TabPage("Noten 2014"),
                new TabPage("History 2013-2010"),
                new TabPage("Sonstiges")});
    }


            for (int i = 0; i <= 3; i++)
            {
                tc.TabPages[i].AutoScroll = true;       
            }
1

There are 1 answers

0
Hans Passant On BEST ANSWER

The complaint is vague, you certainly won't have any trouble operating the scrollbars. I have to guess that your real problem is related to the mouse wheel. Mouse wheel messages are sent to the control that has the focus. Which will be the TabControl when you click a tab. It doesn't have any use for the scroll message, it is the client tab page that implements the scrolling.

So the likely workaround you are looking for is automatically moving the focus to a control inside the tab page right after the tab is selected. Implement an event handler for the SelectedIndexChanged event:

    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {
        var page = tabControl1.SelectedTab;
        page.SelectNextControl(page, true, true, true, true);
    }

It is however not a perfect solution, it still won't work correctly when you use the Tab or cursor keys to navigate to the tab control. Or if the tab page doesn't have any controls that can receive the focus. The more universal solution requires a more surgery, you'd need to forward the mouse wheel message from the tab control to the active tab page. Add a new class to your project and paste the code shown below. Compile. Drag the new control from the top of the toolbar onto your form, replacing the existing one.

using System;
using System.Windows.Forms;

class TabControlEx : TabControl {
    private bool recurse;
    protected override void WndProc(ref Message m) {
        const int WM_MOUSEWHEEL = 0x20a;
        if (!recurse && m.Msg == WM_MOUSEWHEEL && this.SelectedTab != null) {
            recurse = true;
            SendMessage(this.SelectedTab.Handle, m.Msg, m.WParam, m.LParam);
            recurse = false;
            m.Result = IntPtr.Zero;
            return;
        }
        base.WndProc(ref m);
    }
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}