C# winform ListBox实现滚动条自动滚动至底部

效果如图:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading;
 9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11 
12 namespace ListBoxAutoScroll
13 {
14     public partial class Form1 : Form
15     {
16         Thread[] threadArr = new Thread[20];
17         bool scroll = false;
18         object obj = new object();
19         delegate void AddItemCallback(string text);
20         public Form1()
21         {
22             InitializeComponent();
23         }
24 
25         private void btnStart_Click(object sender, EventArgs e)
26         {
27             listBoxMsg.Items.Clear();
28             for (int i = 0; i < threadArr.Length; i++)
29             {
30                 if (threadArr[i] == null || threadArr[i].ThreadState == ThreadState.Aborted || threadArr[i].ThreadState == ThreadState.Stopped)
31                 {
32                     threadArr[i] = new Thread(new ThreadStart(() => AddData(i)));
33                     threadArr[i].Name = i.ToString();
34                 }
35                 threadArr[i].Start();
36             }
37         }
38         public void AddData(int i)
39         {
40 
41             while (true)
42             {
43                 AddItem("ListBox中添加【第" + i.ToString() + "项】");
44                 Thread.Sleep(1000);
45             }
46         }
47         private void AddItem(string text)
48         {
49             if (this.listBoxMsg.TopIndex == this.listBoxMsg.Items.Count - (int)(this.listBoxMsg.Height / this.listBoxMsg.ItemHeight))
50                 scroll = true;
51             if (this.listBoxMsg.InvokeRequired)
52             {
53                 AddItemCallback d = new AddItemCallback(AddItem);
54                 this.Invoke(d, new object[] { text });
55             }
56             else
57             {
58                 this.listBoxMsg.Items.Add(text);
59             }
60             if (scroll)
61                 this.listBoxMsg.TopIndex = this.listBoxMsg.Items.Count - (int)(this.listBoxMsg.Height / this.listBoxMsg.ItemHeight);
62         }
63 
64         private void btnStop_Click(object sender, EventArgs e)
65         {
66             for (int i = 0; i < threadArr.Length; i++)
67             {
68                 if (threadArr[i] != null && threadArr[i].ThreadState != ThreadState.Stopped && threadArr[i].ThreadState != ThreadState.Aborted)
69                 {
70                     threadArr[i].Abort();
71                 }
72             }
73         }
74     }
75 }

转载信息:

原作者:程序届卡卡罗特 

来源:CSDN 

原文:https://blog.csdn.net/u010533180/article/details/73468057
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/seanyan/p/10231545.html