当前位置:网站首页>C# ListBox用法

C# ListBox用法

2022-06-09 13:21:00 熊思雨

在Winform中,ListBox用来显示日志还不错,如图:

用法:

/// <summary>
/// 添加普通日志
/// </summary>
/// <param name="content">内容</param>
public void AddOrdinaryLog(string content)
{
    if (this.InvokeRequired)
    {
        //切换到UI线程
        this.Invoke(new MethodInvoker(delegate
        {
            AddOrdinaryLog_UI(content);
        }));
    }
    else
    {
        AddOrdinaryLog_UI(content);
    }
}


private void AddOrdinaryLog_UI(string content)
{
    //读取当前ListBox列表长度
    int len = ListBox_OrdinaryLogList.Items.Count;
    //插入新的一行
    ListBox_OrdinaryLogList.Items.Insert(len, content);
    //列表长度大于30,那么就删除第1行的数据
    if (len > 30)
        ListBox_OrdinaryLogList.Items.RemoveAt(0);
    //插入新的数据后,将滚动条移动到最下面
    int visibleItems = ListBox_OrdinaryLogList.ClientSize.Height / ListBox_OrdinaryLogList.ItemHeight;
    ListBox_OrdinaryLogList.TopIndex = Math.Max(ListBox_OrdinaryLogList.Items.Count - visibleItems + 1, 0);
}

这里我加了一个线程的判断,不需要直接复制 AddOrdinaryLog_UI 这个方法即可。

end

原网站

版权声明
本文为[熊思雨]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_38693757/article/details/125186731