using System; using System.Windows.Forms; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common { class FocusState { public Control control; public int scrollPosVertical; public int scrollPosHorizontal; } class TabControlFocus { private List lastFocusedControls = new List(); private int focusedTabIndex = 0; public TabControl tabControl = null; private void UpdateListSize() { if (tabControl != null) { while (lastFocusedControls.Count < tabControl.TabPages.Count) lastFocusedControls.Add(new FocusState()); while (lastFocusedControls.Count > tabControl.TabPages.Count) lastFocusedControls.RemoveAt(lastFocusedControls.Count - 1); } } public void SetupTabControl(TabControl tabControl) { this.tabControl = tabControl; tabControl.SelectedIndexChanged += delegate (object sender, EventArgs e) { TabControl parentTabControl = (sender as TabControl); Control control = null; UpdateListSize(); if (parentTabControl.SelectedIndex != -1) { control = lastFocusedControls[parentTabControl.SelectedIndex].control; if (control != null) { control.Focus(); // Restore strollbars position of nearest parent panel with autoscroll while (control.Parent != null) { if ((control.Parent is Panel) && (control.Parent as Panel).AutoScroll) { (control.Parent as Panel).VerticalScroll.Value = lastFocusedControls[parentTabControl.SelectedIndex].scrollPosVertical; (control.Parent as Panel).HorizontalScroll.Value = lastFocusedControls[parentTabControl.SelectedIndex].scrollPosHorizontal; (control.Parent as Panel).PerformLayout(); break; } control = control.Parent; } } } focusedTabIndex = parentTabControl.SelectedIndex; }; } private void TrackLostFocus(object sender, EventArgs e) { Control item = (Control)sender; Control control = (Control)sender; UpdateListSize(); if (!(control is Panel)) while (item.Parent != null) { if (item.Parent is TabPage) { int index = tabControl.TabPages.IndexOf(item.Parent as TabPage); if (index != -1) { if (focusedTabIndex == tabControl.SelectedIndex) { lastFocusedControls[index].control = control; // Store scrollbars position of nearest parent panel with autoscroll while (control.Parent != null) { if ((control.Parent is Panel) && (control.Parent as Panel).AutoScroll) { lastFocusedControls[index].scrollPosVertical = (control.Parent as Panel).VerticalScroll.Value; lastFocusedControls[index].scrollPosHorizontal = (control.Parent as Panel).HorizontalScroll.Value; break; } control = control.Parent; } break; } } } item = item.Parent; } } public void TrackLostFocusOnChildControls(Control.ControlCollection controls) { foreach (Control control in controls) { control.LostFocus += new EventHandler(TrackLostFocus); Control.ControlCollection childControls = control.Controls; if (childControls != null) TrackLostFocusOnChildControls(childControls); } } } }