实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | public partial class ui_log : ListBox { public ui_log() { InitializeComponent(); this .DrawMode = DrawMode.OwnerDrawFixed; this .BackColor = Color.Black; this .Font = new Font( "黑体" , 12); } protected override void OnPaint(PaintEventArgs pe) { base .OnPaint(pe); } protected override void OnDrawItem(DrawItemEventArgs e) { base .OnDrawItem(e); if (e.Index >= 0 && this .Items.Count>0) { dynamic item = this .Items[e.Index]; Brush brush = new SolidBrush(item.Color); e.Graphics.DrawString(item.Text, e.Font, brush, e.Bounds, StringFormat.GenericDefault); } } public void Log( string text, Color color) { if ( this .InvokeRequired) { this .Invoke( new Action(() => { Log(text, color); })); return ; } this .Items.Add( new { Color = color, Text = text }); this .SelectedIndex = this .Items.Count - 1; } public void LogInfo( string text) { Log(text, Color.Green); } public void LogError( string text) { Log(text, Color.Red); } public void LogWarinig( string text) { Log(text, Color.Yellow); } public void ClearLog() { this .Items.Clear(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private void button1_Click( object sender, EventArgs e) { ui_log1.LogInfo( "Info" ); Thread.Sleep(300); ui_log1.LogError( "Error" ); Thread.Sleep(300); ui_log1.LogWarinig( "Warinig" ); Thread.Sleep(300); ui_log1.Log( "White" , Color.White); } private void button2_Click( object sender, EventArgs e) { ui_log1.ClearLog(); } |
代码解析:首先是写了一个自定义控件,继承自ListBox;然后设置下DrawMode属性,这个很重要,否则不会触发DrawItem;最后在DrawItem事件中,对数据进行重绘。
做完上述处理后,就不要直接使用Items.Add了,需要对Items.Add也进行一次封装,将颜色也传进去,即:this.Items.Add(new { Color = color, Text = text });
使用方法:
如果将以下自定义控件放到控件库中(即在新建项目的时候选择Windows窗体控件库),在其他程序中使用起来就很方便了,只要将这个dll拖到工具箱面板中,就可以在工具箱中看到这个控件。使用的时候直接从工具箱中拖出来就可以了。
在通往幸福道路上,并没有什么捷径可走,唯有付出努力和拼搏
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗