Recipe 4.4. Working with Timers


Problem

You need to have some action occur on a regular basis in your form.

Solution

Sample code folder: Chapter 04\ClockTimer

Use a Timer control, and set it for the desired interval. Create a new Windows Forms application, and add a Label control named CurrentTime to the form. Also add a Timer control to the form, and name it ClockTimer. Set its Interval property to 1000, and set its Enabled property to true. 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's Interval property sets the time between Tick events in milliseconds (1,000 per second). Although you can set the Interval as low as one millisecond, the timer's resolution is limited by your system's hardware and operating-system-level factors.

The Tick event fires at approximately the interval you specify, if nothing more important is going on. If the code within your Tick event handler is still running when the next Tick event should occur, that subsequent Tick 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.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net