2014-07-05 28 views
1

我一直在嘗試瞭解如何在Visual Basic中使用定時器(我正在使用Visual Studio 2013 Professional),因爲我只是開始了。我寫了一小段代碼來打開一個表單(包含一個標籤,用黑色文字閱讀「歡迎」,所以我不會出現),這會啓動一個計時器來觸發不同的句子。下面是代碼:出於某種原因,我在Visual Basic中的表單不會顯示

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()',它顯示,但它只是沒有響應或顯示任何東西。

這是所有學習之用,所以請隨時撕碎我的代碼,並告訴我,我所做的每一個錯誤,但請吧:)

+0

你爲什麼用VBA標記這個? –

+0

將'EventsLine'代碼放入Timer Tick中,也許使用稍長的時間間隔,也許可以使用'TextLabel.Refresh'來強制新文本在打開後顯示 – Plutonix

回答

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 
0

的基本問題很好的地方在於你使用與UI線程在同一線程上運行的計時器,並且UI線程被EventsLine方法(從Load事件調用)阻塞。由於事件消息循環永遠不會到達Tick處理程序,所以永遠沒有機會增加計時器滴答。

我建議閱讀.NET中定時器之間的差異。其中一些更適合多線程操作。這是一個很好的資源:

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

而且,你可能也想了解一些關於事件驅動的應用功能的方式。 http://en.wikipedia.org/wiki/Event_loop

相關問題