C#实现item自定义颜色的ListBox,显示日志

来源:互联网 发布:长城宽带是什么网络 编辑:程序博客网 时间:2024/05/18 14:13
一、说明

ListBox自身的OnDrawItem函数是专门绘制item样式的,只需要重载即可

protected override void OnDrawItem(DrawItemEventArgs e)        {            e.DrawBackground();            e.DrawFocusRectangle();            // 确保listbox中有日志且该日志被记录在字典中            if (e.Index >= 0 && m_dicItems.Keys.Contains(e.Index))            {                e.Graphics.DrawString(m_dicItems[e.Index].info, Font, new SolidBrush(m_dicItems[e.Index].color), e.Bounds);            }        }

注意,listBox一定要设置成

this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;

二、那么就开始实现,添加一个组件继承自ListBox

1.先定义一个结构,用于保存item的index、info和color

class LogItem    {        public String info;        public int index;        public Color color;    }

2.再定义一个字典,用于保存已经插入的item

Dictionary<int, LogItem> m_dicItems = new Dictionary<int, LogItem>();

3.拓展一下,日志可以无限制的添加,但是我们可以控制显示的最大条数

private int m_nMaxLength = 1000;        [CategoryAttribute("自定义")]        [DescriptionAttribute("日志最大显示条数")]        public int MaxLength        {            set            {                m_nMaxLength = value;            }            get            {                return m_nMaxLength;            }        }

4.实现两个公共接口

public void AddLog(String log, Color color)public void Clear()

AddLog

创建LogItem并将其添加到m_dicItems中,key就是Add的返回值,即Item在listbox中的位置

Clear

调用ListBox的Clear,同时调用m_dicItem.Clear

5.在实现一个内部的方法,当日志数达到上限时的处理方法
ModefyItems,这个方法的目的就是为了,确保ui显示的内容和m_dicItem中保存的保持一致,那样OnDrawItem才会保证不会绘制有问题
大致思路是,listBox删除0索引的项,m_dicItem中的key不变,value从n+1移到n上,再删除最后一个就ok拉

6.展示一下效果图

7.通过上面的步骤,应该都能实现效果了。demo程序及源码下载地址(为懒人而备)

源码下载