LogControl.cs 2.0 KB
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoScanAndLabel
{
    public partial class LogControl : UserControl
    {
        public LogControl()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            showLogProDelegate = new ShowLogProDelegate(ShowLogPro);
            //LogUtil.ShowLog += LogUtil_ShowLog;
            
        }
        delegate void ShowLogProDelegate(string msg, Color color);
        ShowLogProDelegate showLogProDelegate;
        private void LogUtil_ShowLog(string msg, Color color)
        {
            if (this.InvokeRequired)
                this.Invoke(showLogProDelegate, msg, color);
            else
                ShowLogPro(msg, color);
        }

        private List<string> logList = new List<string>();
        public int showCount = 30;
        private void ShowLogPro(string msg, Color color)
        {
            if(Monitor.TryEnter(logBox))
            {
                try
                {
                    if (logList.Count >= showCount)
                    {
                        logList.RemoveAt(0);
                    }

                    DateTime now = DateTime.Now;
                    logList.Add(now.ToLongTimeString() + "  " + msg + Environment.NewLine);
                    logBox.Text = string.Join("", logList);
                    logBox.Select(logBox.Text.Length, 0);
                    logBox.ScrollToCaret();

                }
                catch (Exception ex)
                {
                    LogUtil.error("出错:" + ex.ToString());
                }
                finally
                {
                     Monitor.Exit(logBox);
                }
            }

        }

        private void LogControl_Load(object sender, EventArgs e)
        {

        }
    }
}