namespace Delegates { partial class Form1 : Form { public Form1() { InitializeComponent(); clock = new Clock(digital); } private void start_Click(object sender, System.EventArgs e) { this.clock.Start(); } private void stop_Click(object sender, System.EventArgs e) { this.clock.Stop(); } private Clock clock; } }
Clock.cs类的内容
namespace Delegates { using System.Windows.Forms; class Clock { public Clock(TextBox displayBox) { this.display = displayBox; } public void Start() { pulsed.Add(this.RefreshTime); } public void Stop() { pulsed.Remove(this.RefreshTime); } private delegate void InvokeCallback(string msg); private void RefreshTime(int hh, int mm, int ss) { if (!this.display.InvokeRequired) { this.display.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", hh, mm, ss); } else { InvokeCallback msgCallback = new InvokeCallback(DisplayText); display.Invoke(msgCallback, new object[] { string.Format("{0:D2}:{1:D2}:{2:D2}", hh, mm, ss) }); } } private void DisplayText(string text) { this.display.Text = text; } private Ticker pulsed = new Ticker(); private TextBox display; } }
namespace Delegates { using System.Collections; using System.Timers; using System.Windows.Forms; class Ticker { public delegate void Tick(int hh, int mm, int ss); public Ticker() { this.ticking.Elapsed += new ElapsedEventHandler(this.OnTimedEvent); this.ticking.Interval = 1000; // 1 second this.ticking.Enabled = true; } public void Add(Tick newMethod) { this.tickers += newMethod; } public void Remove(Tick oldMethod) { this.tickers -= oldMethod; } private void Notify(int hours, int minutes, int seconds) { if (this.tickers != null) { this.tickers(hours, minutes, seconds); } } private void OnTimedEvent(object source, ElapsedEventArgs args) { int hh = args.SignalTime.Hour; int mm = args.SignalTime.Minute; int ss = args.SignalTime.Second; Notify(hh, mm, ss); } private Tick tickers; private System.Timers.Timer ticking = new System.Timers.Timer(); } }
Ticker.cs类的内容