由于某种原因,我在Visual Basic中的表单将不会显示

时间:2014-07-05 00:43:08

标签: vb.net visual-studio

我正在四处尝试学习在Visual Basic中使用计时器(我使用的是Visual Studio 2013 Professional),因为我刚刚开始。我写了一段简短的代码来打开一个表单(包含一个标签,上面写着黑色文本中的“欢迎”,所以我不会出现),这会启动一个会触发不同句子的计时器。这是代码:

Public Class Form1

Private TimerTicks As Integer = Nothing
Private userName As String = "Phillip"

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.BackColor = Color.Black
    Timer.Interval = 1000
    Timer.Enabled = True
    TextLabel.ForeColor = Color.Black
    TextLabel.BackColor = Color.Black
    EventsLine()
End Sub

Private Sub EventsLine()

    Do Until TimerTicks = 20
        If TimerTicks = 1 Then
            TextLabel.ForeColor = Color.White
        ElseIf TimerTicks = 3 Then
            TextLabel.Text = "Your name is " & userName & ", right?"
        ElseIf TimerTicks = 10 Then
            TextLabel.Text = "Nice to meet you"
        End If
    Loop

    Me.Hide()

End Sub


Private Sub Timer_Tick() Handles Timer.Tick
    TimerTicks = TimerTicks + 1
End Sub
End Class

我的代码显然存在可怕的错误,因为当我运行程序时,表单甚至都没有显示出来。我不知道它是在加载还是只是隐藏,因为我尝试在'Form1_Load'Sub中使用'Me.Show()'并显示,但它只是没有响应或显示任何内容。

这一切都是出于学习目的,所以请随意撕开我的代码并告诉我我犯过的每一个错误,但请相信它:)

2 个答案:

答案 0 :(得分:1)

将'Private Sub EventsLine()放入计时器但不使用do,然后才能工作 如果你使用If TimerTicks< 20然后,你也一样。

Private TimerTicks As Integer = Nothing
Private userName As String = "Phillip"

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.BackColor = Color.Black
    Timer.Interval = 1000
    Timer.Enabled = True
    TextLabel.ForeColor = Color.Black
    TextLabel.BackColor = Color.Black

End Sub


'Private Sub EventsLine()

'    Do Until TimerTicks = 20
'        If TimerTicks = 1 Then
'            TextLabel.ForeColor = Color.White
'        ElseIf TimerTicks = 3 Then
'            TextLabel.Text = "Your name is " & userName & ", right?"
'        ElseIf TimerTicks = 10 Then
'            TextLabel.Text = "Nice to meet you"
'        End If
'    Loop

'    Me.Hide()

'End Sub


Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
    TimerTicks = TimerTicks + 1
    If TimerTicks < 20 Then
        If TimerTicks = 1 Then
            TextLabel.ForeColor = Color.White
        ElseIf TimerTicks = 3 Then
            TextLabel.Text = "Your name is " & userName & ", right?"
        ElseIf TimerTicks = 10 Then
            TextLabel.Text = "Nice to meet you"
        End If

    Else

    End If


    If TimerTicks = 20 Then
        Me.Hide()
    End If

End Sub

答案 1 :(得分:0)

基本问题是您正在使用与UI线程在同一线程上运行的计时器,并且EventsLine方法阻止了UI线程(从{{1}调用事件)。由于事件消息循环永远不会到达Load处理程序,因此永远不会有机会增加计时器滴答。

我建议阅读.NET中计时器之间的差异。其中一些更适合多线程操作。这是一个很好的资源:

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

此外,您可能还想了解事件驱动的应用程序的运行方式。 http://en.wikipedia.org/wiki/Event_loop