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);
}
}
}
AppEvents Class
private delegate void RefreshAgentStatus(AgentStatus status);
private delegate void FlushOutPut(string msg);
Form窗体创建委托定义有参无返回值类型委托
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 + "\r\n" + richLog.Text).Substring(0, 500);
}
else
{
richLog.Text = (st + "\r\n" + richLog.Text);
}
}
}
委托事件做的具体事务
private void writeLogToText(string strlog = "")
{
AppEvents.Instance.OnUpdateScreenRun(strlog);
//richLog.Text = richLog.Text + strlog + " \r\n";
}
调用