Custom scrollbar for panel does not scroll smoothly

Viewed 122

customBtn1 is the custom scrollbar. The below code sample works, but the scrolling action is jittery and stuttery. It does not scroll smoothly. Any idea why this could be happening and how to fix it?

    int PreviousBarLoc;
    private void MainForm_Load(object sender, EventArgs e)
    {
        PreviousBarLoc= customBtn1.Location.Y;
    }

    //move the scrollbar up and down when the user drags it
    private void customBtn1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        { MouseDownLocation = e.Location; }
    }
    private Point MouseDownLocation;
    private void customBtn1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            customBtn1.Top = e.Y + customBtn1.Top - MouseDownLocation.Y;
        }
    }
    
    //scroll the panel
    private void customBtn1_LocationChanged(object sender, EventArgs e)
    {
        int locDifference = customBtn1.Location.Y - PreviousBarLoc;
        if (steamSrvListPnl.VerticalScroll.Value + locDifference <= 255 && steamSrvListPnl.VerticalScroll.Value + locDifference >= 0)
        {
            steamSrvListPnl.VerticalScroll.Value += locDifference;
        }
        PreviousBarLoc= customBtn1.Location.Y;

    }
1 Answers

Your deltas are not quite right. The way it is currently written, if you drag the mouse down and then start dragging back up, it will not scroll back up because your current e.Y is still below the original MouseDownLocation.Y. I'm not entirely sure of your setup, but below is an example of how to get smooth scrolling to work when the left mouse button is pressed and dragged on a button:

    private int _prevY = 0;
    private bool _mouseDown = false;
    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            _mouseDown = true;
            _prevY = e.Y;
        }
    }

    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (_mouseDown)
        {
            panel1.VerticalScroll.Value = Math.Max(panel1.VerticalScroll.Minimum, Math.Min(panel1.VerticalScroll.Maximum, panel1.VerticalScroll.Value + e.Y - _prevY));
            _prevY = e.Y;
        }
    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        if (_mouseDown)
        {
            _mouseDown = false;
            _prevY = 0;
        }
    }
Related