效果如图:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace ListBoxAutoScroll
{
public partial class Form1 : Form
{
Thread[] threadArr = new Thread[];
bool scroll = false;
object obj = new object();
delegate void AddItemCallback(string text);
public Form1()
{
InitializeComponent();
} private void btnStart_Click(object sender, EventArgs e)
{
listBoxMsg.Items.Clear();
for (int i = ; i < threadArr.Length; i++)
{
if (threadArr[i] == null || threadArr[i].ThreadState == ThreadState.Aborted || threadArr[i].ThreadState == ThreadState.Stopped)
{
threadArr[i] = new Thread(new ThreadStart(() => AddData(i)));
threadArr[i].Name = i.ToString();
}
threadArr[i].Start();
}
}
public void AddData(int i)
{ while (true)
{
AddItem("ListBox中添加【第" + i.ToString() + "项】");
Thread.Sleep();
}
}
private void AddItem(string text)
{
if (this.listBoxMsg.TopIndex == this.listBoxMsg.Items.Count - (int)(this.listBoxMsg.Height / this.listBoxMsg.ItemHeight))
scroll = true;
if (this.listBoxMsg.InvokeRequired)
{
AddItemCallback d = new AddItemCallback(AddItem);
this.Invoke(d, new object[] { text });
}
else
{
this.listBoxMsg.Items.Add(text);
}
if (scroll)
this.listBoxMsg.TopIndex = this.listBoxMsg.Items.Count - (int)(this.listBoxMsg.Height / this.listBoxMsg.ItemHeight);
} private void btnStop_Click(object sender, EventArgs e)
{
for (int i = ; i < threadArr.Length; i++)
{
if (threadArr[i] != null && threadArr[i].ThreadState != ThreadState.Stopped && threadArr[i].ThreadState != ThreadState.Aborted)
{
threadArr[i].Abort();
}
}
}
}
}
转载信息:
原作者:程序届卡卡罗特
来源:CSDN
原文:https://blog.csdn.net/u010533180/article/details/73468057
版权声明:本文为博主原创文章,转载请附上博文链接!