
public class AppEvents { private static AppEvents instance = null; private AppEvents() { } public static AppEvents Instance { get { if (instance == null) instance = new AppEvents(); return instance; } } public delegate void UpdateScreenEventHandler(string msg); //委托声明 sunjie 1 public delegate void UpdateConnectionStatusEventHandler(AgentStatus status); public UpdateScreenEventHandler OnUpdateScreenRun; //创建委托对象 sunjie 2 public UpdateConnectionStatusEventHandler OnUpdateConnectionStatusRun; public event UpdateScreenEventHandler UpdateScreenEvent { add { OnUpdateScreenRun = (UpdateScreenEventHandler)System.Delegate.Combine(OnUpdateScreenRun, value); } remove { OnUpdateScreenRun = (UpdateScreenEventHandler)System.Delegate.Remove(OnUpdateScreenRun, value); } } public event UpdateConnectionStatusEventHandler UpdateConnectionStatusEvent { add { OnUpdateConnectionStatusRun = (UpdateConnectionStatusEventHandler)Delegate.Combine(OnUpdateConnectionStatusRun, value); } remove { OnUpdateConnectionStatusRun = (UpdateConnectionStatusEventHandler)Delegate.Remove(OnUpdateConnectionStatusRun, value); } } }

private delegate void RefreshAgentStatus(AgentStatus status); private delegate void FlushOutPut(string msg);

private void InitializeEvents() { AppEvents.Instance.UpdateConnectionStatusEvent += UpdateStatus; AppEvents.Instance.UpdateScreenEvent += LogToScreen; }

public void UpdateStatus(AgentStatus status) { if (lbStatus.InvokeRequired) { var refresh = new RefreshAgentStatus(UpdateStatus); this.Invoke(refresh, new object[] { status }); } else { if (status == AgentStatus.ONLINE) { if (!string.Equals(lbStatus.Text, status.ToString())) { lbStatus.Text = status.ToString(); lbStatus.BackColor = System.Drawing.Color.LimeGreen; lbStatus.ForeColor = System.Drawing.Color.Black; } } else { if (status == AgentStatus.ERROR || status == AgentStatus.OFFLINE) { if (!string.Equals(lbStatus.Text, status.ToString())) { lbStatus.Text = status.ToString(); lbStatus.BackColor = System.Drawing.Color.Red; lbStatus.ForeColor = System.Drawing.Color.White; } } else { //lbStatus.Text = status.ToString(); //lbStatus.BackColor = System.Drawing.Color.LimeGreen; //lbStatus.ForeColor = System.Drawing.Color.Black; } } } } private void LogToScreen(string st) { if (this.richLog.InvokeRequired) { var flush = new FlushOutPut(LogToScreen); this.Invoke(flush, new object[] { st }); } else { var msg = string.Format("{0} {1}", DateTime.Now.ToString(Settings.NormalDateTimeFormatDash), st); if (richLog.Text.Length >= 500) { var index = richLog.Text.Length; richLog.Text = (st + " " + richLog.Text).Substring(0, 500); } else { richLog.Text = (st + " " + richLog.Text); } } }

private void writeLogToText(string strlog = "") { AppEvents.Instance.OnUpdateScreenRun(strlog); //richLog.Text = richLog.Text + strlog + " "; }