Forms, Controls, and Other Useful Objects - 4.4 Working with Timers (Page 4 of 5 )
Problem
You need to have some action occur on a regular basis in your form.
Solution Sample code folder: Chapter 04\ClockTimer
Use aTimercontrol, and set it for the desired interval. Create a new Windows Forms application, and add aLabelcontrol namedCurrentTimeto the form. Also add aTimercontrol to the form, and name itClockTimer. Set itsIntervalproperty to1000, and set itsEnabled property toTrue. Then add the following source code to the form’s code template:
Private Sub ClockTimer_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ClockTimer.Tick
CurrentTime.Text = Now.ToLongTimeString
End Sub
When you run the program, that label updates once each second with the current time.
Discussion The Timer control’sIntervalproperty sets the time betweenTickevents in milliseconds (1,000 per second). Although you can set theIntervalas low as one millisecond, the timer’s resolution is limited by your system’s hardware and operating-system-level factors.
TheTickevent fires at approximately the interval you specify, if nothing more important is going on. If the code within yourTickevent handler is still running when the nextTickevent should occur, that subsequentTick event is disposed without a call to the event handler.
See Also Recipe 14.8 shows how to have a section of code sleep, or take a small break. Some older Visual Basic code used timers for this purpose, although a timer is not the best solution in this case.
Next: 4.5 Determining If a Control Can Take the Focus >>
More Visual Basic.NET Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the Visual Basic 2005 Cookbook, written by Tim Patrick and John Clark Craig (O'Reilly; ISBN: 0596101775). Check it out today at your favorite bookstore. Buy this book now.
|
|