猜测一下,您可能希望显示其他形式,并且可能具有不同的延迟。您可以使用以表单和延迟作为参数的 Sub 来做到这一点。
假设您使用的是 VS2010 或更高版本,您的代码可能如下所示:
Private Sub ShowNextForm(formToShow As Form, secondsDelay As Double)
Dim tim As New System.Windows.Forms.Timer
tim.Interval = CInt(secondsDelay * 1000)
tim.Start()
AddHandler tim.Tick, Sub(sender As Object, e As EventArgs)
tim.Stop()
tim.Dispose()
Me.Hide()
formToShow.Show()
End Sub
End Sub
Private Sub btnAnswerA_Click(sender As Object, e As EventArgs) Handles btnAnswerA.Click
Dim bn = DirectCast(sender, Button)
bn.Enabled = False
bn.BackColor = Color.Green
Dim nextForm As New Q2
ShowNextForm(nextForm, 10)
End Sub
然后,如果你有另一个按钮,你想做同样的事情,说“btnAnswer99”表格z99和延迟2.5秒,你只需要编写代码
Private Sub btnAnswer99_Click(sender As Object, e As EventArgs) Handles btnAnswer99.Click
Dim bn = DirectCast(sender, Button)
bn.Enabled = False
bn.BackColor = Color.Blue
Dim nextForm As New z99
ShowNextForm(nextForm, 2.5)
End Sub
变得更高级...也许稍后再看...
您可能会注意到您为每个按钮重复了很多代码。现在是时候考虑重构你的代码了,这样你只需要编写一次基本的代码,并且有参数来决定它的作用。
因此,您可以查看所有按钮单击处理程序之间的共同点,例如它们都有一个它们所在的表单、一个要显示的表单、一些要更改为的 BackColor,以及显示下一个表单之前的延迟,以及当然,他们指的是 a 按钮。
这是创建一个类来封装所有部分的理想机会,可能有点像这样:
Friend Class SetButtonToShowForm
Property thisForm As Form
Property nextForm As Form
Property buttonRef As Button
Property buttonBackColor As Color
Property secondsDelay As Double
Friend Sub ShowNextForm(currentForm As Form, formToShow As Form, secondsDelay As Double)
Dim tim As New System.Windows.Forms.Timer
tim.Interval = CInt(secondsDelay * 1000)
tim.Start()
AddHandler tim.Tick, Sub(sender As Object, e As EventArgs)
tim.Stop()
tim.Dispose()
currentForm.Hide()
formToShow.Show()
End Sub
End Sub
Friend Sub bnClick(sender As Object, e As EventArgs)
Dim bn = DirectCast(sender, Button)
bn.Enabled = False
bn.BackColor = Me.buttonBackColor
ShowNextForm(thisForm, nextForm, secondsDelay)
End Sub
Public Sub New()
' empty constructor
End Sub
Public Sub New(sourceForm As Form, targetForm As Form, buttonRef As Button, backColor As Color, secondsDelay As Double)
Me.thisForm = sourceForm
Me.nextForm = targetForm
Me.buttonRef = buttonRef
Me.buttonBackColor = backColor
Me.secondsDelay = secondsDelay
AddHandler Me.buttonRef.Click, AddressOf bnClick
End Sub
End Class
然后您可以按照以下步骤在一个过程中设置所有按钮
Private Sub SetButtonHandlers()
Dim b1 As New SetButtonToShowForm(Me, Q2, btnAnswerA, Color.Green, 5)
Dim b2 As New SetButtonToShowForm(Me, z99, btnAnswer99, Color.Blue, 2.3)
End Sub
因此您可以看到,只需一点 多一点努力,就可以更加轻松地设置更多按钮。