我创建了一个继承自System.Windows.Forms.Timer
的新类。在这个类中,我创建了另一个计时器作为使用父类的计时器启用的属性。然后,子计时器计时器报告直到下一个父节拍的时间。
我想避免使用其他方法来启动两个计时器。
我可以以某种方式检查父timer.enabled是否已被更改?这里的问题是,如果我启动父计时器,我必须等待timer.Interval
,直到它第一次打勾。但是我希望子计时器以父计时器开始,以开始报告第一次打勾的时间。
这是我到目前为止所做的事情。
public class LoopTimer : Timer {
public DateTime? NextTickSchedule { get; set; }
public LoopTimer() : base() {
CountdownTimer.Interval = 1000;
CountdownTimer.Tick += CountdownTimer_Tick;
this.Tick += LoopTimer_Tick;
}
public LoopTimer(IContainer container) : base(container) {
CountdownTimer.Interval = 1000;
}
private void LoopTimer_Tick(object sender, EventArgs e) {
OnTick();
}
private void OnTick() {
NextTickSchedule = DateTime.Now.AddMilliseconds(this.Interval);
MinutesUntilNextTick = TimeUntilNextTick.ToString("mm\\:ss");
}
public void StartTimer() {
this.Enabled = CountdownTimer.Enabled = true;
OnTick();
}
public void StopTimer() {
this.Enabled = CountdownTimer.Enabled = false;
NextTickSchedule = null;
MinutesUntilNextTick = "";
TimeUntilNextTick = new TimeSpan();
}
#region Countdown Timer
public Timer CountdownTimer { get; set; } = new Timer();
public TimeSpan TimeUntilNextTick { get; set; } = new TimeSpan();
public string MinutesUntilNextTick { get; set; } = "";
private void CountdownTimer_Tick(object sender, EventArgs e) {
if (NextTickSchedule.HasValue) {
TimeUntilNextTick = NextTickSchedule.Value - DateTime.Now;
MinutesUntilNextTick = TimeUntilNextTick.ToString("mm\\:ss");
}
}
#endregion
}
答案 0 :(得分:2)
您可以覆盖Enabled
属性,并在启用更改时引发事件。然后在子/其他控件中,订阅该事件:
public class MyTimer : Timer
{
public event EventHandler EnabledChanged;
public override bool Enabled
{
get { return base.Enabled; }
set
{
base.Enabled = value;
EnabledChanged?.Invoke(this, EventArgs.Empty);
}
}
}