One thing that all the controls you used in Hour 7, "Working with Traditional Controls," have in common is that the
Create a new Windows Application titled
You probably noticed that there are very few properties for the Timer control, compared to the other controls with which you've worked. The key property of the Timer control is the Interval property. The Interval property determines how often the Timer control fires its Tick event. The Interval is specified in milliseconds, so a setting of 1,000 is equal to 1 second. The best way to understand how the timer works is to use it. Using the Timer and a Label control, you're now going to create a simple clock. The way the clock will work is that the timer will fire its Tick event once every second (because you'll set the Interval = 1000
Add a new label to the form and set its properties as follows:
Next, double-click the Timer control to access its Tick event. When a timer is first enabled, it starts counting, in milliseconds, from 0. When the amount of time specified in the Interval property
DateTime dtCurrentTime = DateTime.Now; lblClock.Text = dtCurrentTime.ToLongTimeString();
The .NET Framework provides date/time functionality in the System namespace. The Now property of the DateTime class returns the current time. Using the ToLongTimeString method returns a string with a time format of hh:mm:ss. Using this class, property, and method, we set the Text property of the label to the current time of day, and it does this once a second. Press F5 to run the project now and you'll see the Label control acting as a clock, updating the time every second (see Figure 8.2).
Stop the running project now and save your work. Timers are powerful, but you must take care not to overuse them. For a timer to work, Windows must be aware of the timer and must constantly compare the current internal clock to the interval of the timer. It does all this so that it can notify the timer at the appropriate time to execute its Tick event. In other words, timers take system resources. This isn't a problem for an application that uses a few timers, but I wouldn't overload an application with a