我正在制作试纸,那里有计数器。当用户点击下一个按钮时,我必须继续它。
我在表格3上用于计时器的代码是:
Public Class Form3
Inherits System.Windows.Forms.Form
Private alarmTime As Date
Private Sub Form3_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.alarmTime = Date.Now.AddMinutes(60)
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
If alarmTime < Date.Now Then
Me.Timer1.Stop()
MessageBox.Show("Time's up.")
Else
Dim remainingTime As TimeSpan = Me.alarmTime.Subtract(Date.Now)
Me.Label6.Text = String.Format("{0}:{1:d2}:{2:d2}", _
remainingTime.Hours, _
remainingTime.Minutes, _
remainingTime.Seconds)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim frmDialogue As New Form8
frmDialogue.ShowDialog()
End Sub
答案 0 :(得分:1)
我会将您计时器的所有代码放入Module
。这样您就可以在应用程序的任何位置访问它。我还要添加两个新事件Elapsed
和TimerComplete
,以便多个对象和表单可以订阅您希望在执行时执行的关键操作计时器滴答。
以下是可从任何地方访问的AppTimer
模块:
Module AppTimer
Private alarmTime As Date
Private WithEvents timer As Timer = New Timer()
Public Sub Start(ByVal time as Date)
alarmTime = time
timer.Start()
End Sub
Public Sub TimerTick(ByVal sender As Object, ByVal e as EventArgs)
Handles timer.Tick
If alarmTime < Date.Now Then
timer.Stop()
RaiseEvent TimerComplete("Time's up.")
Else
Dim remainingTime As Timespan = alarmTime.Subtract(Date.Now)
RaiseEvent Elapsed(remainingTime)
End If
End Sub
'This will fire when the duration of the timer has elapsed
Public Event TimerComplete As Action(Of String)
'This will fire each time the timer ticks unless it's finished
Public Event Elapsed As Action(Of Timespan)
End Module
现在在Form3_Load(...)
你可以像这样设置计时器:
AppTimer.Start(Date.Now.AddMinutes(60))
然后以任何形式,你希望在这些事件触发时做一些事情,创建两个新方法并用AddHandler
连接它们:
AddHandler AppTimer.Elapsed, AddressOf HandleElapsed
AddHandler AppTimer.TimerComplete, AddressOf HandleComplete
Private Sub HandleElapsed(ByVal remainingTime As Timespan)
Me.Label6.Text = String.Format("{0}:{1:d2}:{2:d2}", _
remainingTime.Hours, _
remainingTime.Minutes, _
remainingTime.Seconds)
End Sub
Private Sub HandleComplete(ByVal message As String)
MessageBox.Show(message)
End Sub
还值得注意的是,您可以使用lambdas
:
AddHandler AppTimer.Elapsed, Sub(remainingTime)
String.Format("{0}:{1:d2}:{2:d2}", _
remainingTime.Hours, _
remainingTime.Minutes, _
remainingTime.Seconds)
End Sub
希望这有帮助。
答案 1 :(得分:0)
你可以创建一个主mdi窗口来保存定时器,并且会有子窗口可以访问父定时器,甚至mdi本身可以关闭所有的测试纸形式并显示msg框以便在时间到了。