Using the Timer ControlThe Timer control allows you to execute event-handling code repeatedly in defined intervals. The code will be executed on the same thread that the Windows code is running in. If you need code to run in a thread outside of the Windows thread, then you should use the System.Threading namespace. The Timer control fires by raising a Tick event. A Tick event is raised only when the Timer 's Enabled property is set to true. You can stop a Timer control from firing by setting the Enabled property to false. The Timer control's Interval property defines the number of milliseconds between Tick events.
In the "Programming the ProgressBar Control" section, the BombSquad.exe game was presented. The object of the game was to click the Diffuse button before the ProgressBar control filled up. The trick was that the Diffuse button's location would continuously change, while the ProgressBar 's value increased. This application uses two timers. One Timer control determined how often the ProgressBar 's value was updated. And another Timer control handled moving the Diffuse button around the form. Listing 3.4 demonstrates how these two Timer s are handled. Listing 3.4C# private void timerButtonMove_Tick(object sender, System.EventArgs e) { if(!gameOver) { this.button1.Location = new Point(rand.Next(0, 168), rand.Next(0, 216)); }else { EndGame(); } } private void timerProgressBar_Tick(object sender, System.EventArgs e) { if( counter < 60 ) { if( gameOver ) return; if(this.progressBar1.Value < this.progressBar1.Maximum) this.progressBar1.Value += 1; ++counter; } else { if( !gameOver ) { EndGame(); MessageBox.Show("Boom!", "Loser"); } } } private void EndGame() { this.timerButtonMove.Enabled = false; this.timerProgressBar.Enabled = false; counter = 0; this.gameOver = true; this.button2.Enabled = true; } VB Private Sub timerButtonMove_Tick(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles timerButtonMove.Tick If Not gameOver Then Me.button1.Location = _ New Point(rand.Next(0, 168), rand.Next(0, 216)) Else EndGame() End If End Sub Private Sub timerProgressBar_Tick(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles timerProgressBar.Tick If counter < 60 Then If gameOver Then Return End If If Me.progressBar1.Value < Me.progressBar1.Maximum Then Me.progressBar1.Value = Me.progressBar1.Value + 1 counter = counter + 1 Else If Not gameOver Then EndGame() MessageBox.Show("Boom!", "Loser") End If End If End If End Sub Private Sub EndGame() Me.timerButtonMove.Enabled = False Me.timerProgressBar.Enabled = False counter = 0 Me.gameOver = True Me.button2.Enabled = True End Sub |