Search code examples
c#.netwinformsscrollsmooth-scrolling

How to implement smooth scrolling in .NET


I want to implement a smooth/animated scrolling for a custom control in C#. I want something similar to the following javascript example:

http://www.kryogenix.org/code/browser/smoothscroll/#p0

My first idea is moving the scrollbars to the target point but stopping in intermediate points. For example, this is a very simplified idea:

public void SetSrollValue(int x)
{
    // assume right scrolling
    float step = x / 10;

    while (scroll.Value < x)
    {
        scroll.Value += step;
    }
}

My questions are:

  • Should I implement this in a thread?
  • Will this be painted smoothly (I suppose that yes if I have double buffer activated in my control)

So, if you know any good example, article, guide or similar, please could you provider a link here?

Thanks in advance.


Solution

  • To make the content of the control scroll, you pass the value of the AutoScrollPosition to e.Graphics.TranslateTransform(). That's your angle, alter the value you pass.

    Write a little helper class that observes the value of the control's AutoScrollPosition with a method that you call in your OnPaint method, passing e.Graphics so you can call its TranslateTransform method. When you see it change, record Environment.TickCount, set an internal 'scrollBusy' flag and start a 15 msec timer. On each timer tick, call the control's Invalidate() method so that you'll calculate a new value for TranslateTransform when your method is called again. Calculate the increment from the original to the target scroll position so it takes, say, 250 msec.