C#: Panel Resets Scroll Position after Focus is Lost and Regained


In an application that I have written there is a dashboard on the main form that is composed of a large docked scrollable¬†panel that contains various other panels each showing various pieces of information. I have the AutoScroll property of the panel set to True so that if there are more modules/panels on the dashboard than can be visible on the screen, the user can scroll down to view them. When the user navigates to another window or another application, then returns to my application, and clicks one of the smaller panels on the dashboard, the large docked panel’s scroll position jumps up to the top. This was quite annoying as every time the user returned to my application they had to scroll back down to the module they were looking at previously.

Many of the solutions I found suggested manually setting the Panel.AutoScrollPosition when the form regains focus. The problem with this is that I would have had to capture the Click or MouseDown¬†events of every single control on the form. I figured there had to be a better way to do this so I kept searching. I finally found a post on a forum that indicated that the issue was caused by the fact that the Panel.ScrollToControl¬†method is called when my application regains focus. The ScrollToControl was scrolling to what the Panel control deemed to be the “activeControl” and thus caused the panel to jump to the top. So, to solve my problem, all I did was create a class that extended the Panel class and overrode the ScrollToControl method so that it returned the point associated with the currently visible portion of the panel.

public class CustomPanel : System.Windows.Forms.Panel
{
    protected override System.Drawing.Point ScrollToControl(System.Windows.Forms.Control activeControl)
    {
        // Returning the current location prevents the panel from
        // scrolling to the active control when the panel loses and regains focus
        return this.DisplayRectangle.Location;
    }
}

I presume that this might have side effects elsewhere but I haven’t found any so far in my situation.

Follow

Get every new post delivered to your Inbox.

Join 66 other followers