using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.ComponentModel;
namespace WebTimer
{
public class WebTimer:Control,IPostBackEventHandler
{
#region 成员
private Int32 _interval = 5000;
private Boolean _enabled = false;
private static readonly object EventTimer = new object();
#endregion
#region属性
[DefaultValue(5000),Bindable(false),Description("延迟毫秒数")]
public Int32 Interval
{
get { return _interval; }
set { _interval = value; }
}
public Boolean Enable
{
get { return _enabled; }
set { _enabled = value; }
}
#endregion
/// <summary>
/// 定义事件
/// </summary>
#region 事件
public event EventHandler Timer
{
add {
//将委托添加到控件的委托列表中,value是一个委托,此方法包含
//this.Timer+=EventHandler(Id_Timer);
Events.AddHandler(EventTimer, value);
}
remove {
Events.RemoveHandler(EventTimer, value);
}
}
/// <summary>
/// 在执行时postback时调用
/// </summary>
/// <param name="e"></param>
protected virtual void OnTimer(EventArgs e)
{
EventHandler timerHandler = (EventHandler)Events[EventTimer];
if (timerHandler != null)
{ //执行所有向Timer事件注册的方法:ID_Timer(sender,e)
timerHandler(this, e);
}
}
#endregion
/// <summary>
/// 实现接口:在PostBack事件中调用OnTimer函数
/// </summary>
/// <param name="eventArgument"></param>
#region 接口
public void RaisePostBackEvent(string eventArgument)
{
//事件发生调用OnTimer函数
OnTimer(EventArgs.Empty);
}
#endregion
#region 核心Js:setTimeOut函数
private string buildJs()
{
StringBuilder str = new StringBuilder();
str.Append("<script language='JavaScript'>\n<!-- ");
str.AppendFormat("\n setTimeout(\"{0}\",{1});",
new object[] { this.Page.GetPostBackEventReference(this), _interval.ToString() });
str.Append("\n//-->\n</script>");
return str.ToString();
}
#endregion
#region 重载OnPreRender、Render
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
Page.GetPostBackEventReference(this, "");
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
if (Page!=null)
{
Page.VerifyRenderingInServerForm(this);
}
if (_enabled)
{
writer.Write(buildJs());
}
}
#endregion
}
}