目录
  • 文章描述
  • 开发环境
  • 开发工具
  • 实现代码
  • 实现效果

文章描述

一般情况下,我们的日志文件是用来记录一些关键操作或者异常,并且是后台存储,并不对外开放的;但是也有些时候,特别是做一些小工具程序,需要将一些操作步骤、记录等直接显示在窗体上。以便于使用者能够知道执行进度等情况。

所以,我们可以简单封装一下,写个专门用来输出日志的控件;并且以不同的颜色表示不同的状态,让日志更直观明了。

如果将以下自定义控件放到控件库中(即在新建项目的时候选择Windows窗体控件库),在其他程序中使用起来就很方便了,只要将这个dll拖到工具箱面板中,就可以在工具箱中看到这个控件。使用的时候直接从工具箱中拖出来就可以了。

C#实现UI控件输出日志的方法详解

开发环境

.NET Framework版本:4.5

开发工具

Visual Studio 2013

实现代码

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();
        }
    }
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();
        }

实现效果

C#实现UI控件输出日志的方法详解

代码解析:首先是写了一个自定义控件,继承自ListBox;然后设置下DrawMode属性,这个很重要,否则不会触发DrawItem;最后在DrawItem事件中,对数据进行重绘。

做完上述处理后,就不要直接使用Items.Add了,需要对Items.Add也进行一次封装,将颜色也传进去,即:this.Items.Add(new { Color = color, Text = text });

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。