我有以下代码; 我添加了第二个表单并以编程方式控制它,但计时器在第二个表单中无法正常工作; 当然它以主要形式正常运作; 在第二种形式中,我需要帮助,就像我在主要形式中所做的一样; 提前感谢您的帮助;
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim frmNew As New Form
frmNew.Visible = True
Dim Label2 As New Label()
frmNew.Controls.Add(Label2)
Label2.Name = "Label1"
oTimer = New System.Windows.Forms.Timer
oTimer.Interval = 1000
oTimer.Enabled = True
oTimer.Start()
frmNew.Text = Date.Now
Label2.Text = Date.Now
End Sub
Private WithEvents oTimer As System.Windows.Forms.Timer
Private Sub timerTicks() Handles oTimer.Tick
Me.Text = Date.Now
label1.text = Date.Now
'frmNew.Text = Date.Now
'frmNew.Label2.Text = Date.Now
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
答案 0 :(得分:1)
您需要以某种方式将对Form和Label的引用传递给Timer的Tick()事件。这是一种方法:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim frmNew As New Form
Dim Label2 As New Label()
frmNew.Controls.Add(Label2)
Dim tmr As New System.Windows.Forms.Timer
AddHandler tmr.Tick, AddressOf tmr_Tick
tmr.Tag = New Tuple(Of Control, Control)(frmNew, Label2)
tmr.Interval = 1000
tmr.Start()
frmNew.Text = Date.Now
Label2.Text = Date.Now
frmNew.Show()
End Sub
Private Sub tmr_Tick(sender As Object, e As EventArgs)
Dim T As Tuple(Of Control, Control) = DirectCast(DirectCast(sender, System.Windows.Forms.Timer).Tag, Tuple(Of Control, Control))
Dim frm As Form = DirectCast(T.Item1, Form)
Dim lbl As Label = DirectCast(T.Item2, Label)
Dim curTime As String = DateTime.Now.ToString("h:mm:ss tt")
frm.Text = curTime
lbl.Text = curTime
End Sub
End Class