细胞de理想

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  106 随笔 :: 1 文章 :: 4 评论 :: 11万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

实现代码:

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拖到工具箱面板中,就可以在工具箱中看到这个控件。使用的时候直接从工具箱中拖出来就可以了。

posted on   细胞的理想  阅读(79)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示