listbox auto scroll down

YUI-012 160 Reputation points
2025-02-08T10:16:21.3966667+00:00

1

I have a listbox and checkbox, Now I want is If I click the checkbox name scroll down the listbox well be scroll down automatically with a normal speed, not to fast and not to slow.

I have a sample code:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
			timer2.Start();//start scroll
		}


In this code I tried to use timer_tick.

private void timer2_Tick(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
            }
        }

The problem of this code is can scroll in listbox but supper fast.

I already check the interval of timer but still not working properly.

1

Please someone can help me to fix my problem. Thank you so much in advance.

Developer technologies Visual Studio Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2025-02-08T11:38:24.4966667+00:00

    Try to replace listBox1.SelectedIndex = listBox1.Items.Count - 1 with ++listBox1.TopIndex;

    You can also stop the timer and uncheck the checkbox programmatically if there are no more items to scroll.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2025-02-08T11:24:28.1633333+00:00

    You can do something like this :

            private const int WM_VSCROLL = 0x0115;
            private const int SB_LINEUP = 0;     
            private const int SB_LINEDOWN = 1;    
            private System.Windows.Forms.Timer scrollTimer;
            private int nSrollSteps = 0;
            private int nTotalSteps = 0;
    
            [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
            public static extern int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
    
    
    {
        scrollTimer = new System.Windows.Forms.Timer();
        scrollTimer.Interval = 100;
        scrollTimer.Tick += ScrollStep;
        nTotalSteps =  listBox1.Items.Count - listBox1.ClientSize.Height / listBox1.ItemHeight;
        nSrollSteps = 0;
        scrollTimer.Start();
    }
    
            private void ScrollStep(object sender, EventArgs e)
            {
                if (nSrollSteps < nTotalSteps)
                {
                    SendMessage(listBox1.Handle, WM_VSCROLL, (IntPtr)SB_LINEDOWN, IntPtr.Zero);
                    nSrollSteps++;
                }
                else
                {
                    Console.Beep(5000, 10);
                    scrollTimer.Stop();
                }
            }
    
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.