C# 入门一一事件(event)的应用:如何在TextBox控件中实时显示Log

上一章节我们介绍了事件(event)的相关用法,那么我们利用所学知识,实现在TextBox控件中实时显示Log的一个功能。

同样,针对事件,我们需要明确事件的两类角色:

1.事件发布者:是指触发事件的对象,本例中,Log每写一行数据便触发相应事件

2.事件订阅者:是指捕获事件并作出相应处理,本例中,捕获到Log每次写入一行这个事件,作出实时在TextBox控件中显示的处理

接下来,我们按照事件使用的相关步骤:

一、定义事件

public event EventHandler<LogEventArgs> LogEvent;
public class LogEventArgs : EventArgs
{
	public string Message
	{
		set;
		get;
	}
}

二、添加事件处理函数(由事件订阅者提供,即TextBox所在部分)

注意:事件处理函数的定义需要与委托的定义保持一致,即其参数个数、参数类型和返回类型等需要与委托相同。

此处为EventHandler<LogEventArgs>,所以其定义与委托保持一致,如下:

private void ShowLog( object sender, LogEventArgs msg )
{
	//if( this.InvokeRequired )
	{
		BeginInvoke( new AddLogDelegate( RichTextBoxAddLine ), msg.Message );
	}
}
private void RichTextBoxAddLine( string msg )
{
	this.RTBox_Log.AppendText( msg.TrimEnd( ) + "\n" );
}

三、事件绑定/取消

m_Loger.LogEvent += new EventHandler<LogEventArgs>( ShowLog );

四、事件触发(由事件发布者提供,即Log打印部分)

public virtual void WriteLine( string str_fmt, params object[ ] args )
{
	Monitor.Enter( this );
	try
	{
		LogEventArgs logArgs = new LogEventArgs( );
		logArgs.Message = GetTime( ) + string.Format( str_fmt, args );

		if( null != m_Log )
		{
			m_Log.WriteLine( logArgs.Message );
		}
		if( LogEvent != null )
		{
			LogEvent( this, logArgs );
		}
	}
	catch( Exception e )
	{
		Debug.WriteLine( e.Message );
	}
	finally
	{
		Monitor.Exit( this );
	} 
}

这样,通过调用,我们就可以实现在TextBox控件上实时显示Log信息了

m_Loger.WriteLine( "IP={0},Port={1}",strIP,iPort);

C# 入门一一事件(event)的应用:如何在TextBox控件中实时显示Log

完整测试用例代码链接如下:

https://download.****.net/download/xuanyin235/11007263