View Single Post
Old 03-23-2014, 04:17 PM
Gruff's Avatar
Gruff Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default CountDownTimer Class

Here is a simple Count down Timer inherited from a standard Timer.
If CountEnabled is false it behaves as a standard timer.

Otherwise it allows a built in count down (or count up) from CountStart to CountStop at CountStep.

I am using it to simplify fading graphics. It allows itself to be interrupted short circuiting the fade.
' Class code for new CountDownTimer ' --- Public Class CountDownTimer Inherits Timer Public Event CountReset() Public Property CountEnabled As Boolean = False Public Property CountStart As Integer = 255 Public Property CountStop As Integer = 0 Public Property CountStep As Integer = -1 Public Property CountLoop As Boolean = True Public Property CountValue As Integer = CountStart Public Sub CountRestart() CountValue = CountStart End Sub Protected Overrides Sub OnTick(e As System.EventArgs) MyBase.OnTick(e) If CountEnabled Then CountValue += CountStep If CountValue = CountStop Then CountValue = CountStart If CountLoop Then RaiseEvent CountReset() Else Me.Enabled = False End If End If End If End Sub End Class
' Form Code using the CountDownTimer ' ---- Imports System.Drawing Public Class Form1 Dim g As Graphics = Me.CreateGraphics Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 'All of these properties may be set at Design-Time With CountDownTimer1 .Interval = 10 .CountEnabled = True .CountStart = 255 .CountStop = 100 .CountStep = -1 .CountValue = 255 .CountLoop = True End With End Sub Private Sub CountDownTimer1_Tick(sender As System.Object, e As System.EventArgs) Handles CountDownTimer1.Tick With g Dim FadeColor As Color = Color.FromArgb(255, CountDownTimer1.CountValue, 0, 0) Using B As Brush = New SolidBrush(FadeColor) .FillRectangle(B, 20, 20, 40, 40) End Using End With End Sub Private Sub CountDownTimer1_CountReset() Handles CountDownTimer1.CountReset ' Do something when cycle restarts End Sub Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click CountDownTimer1.CountRestart() CountDownTimer1.Start() End Sub Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click CountDownTimer1.Stop() End Sub End Class

Have Fun
Burn the land and boil the sea
You can't take the sky from me

Reply With Quote