Chapter 8
The Timer
The Microsoft Windows timer is an input device that periodically notifies an application when a specified interval of time has elapsed. Your program tells Windows the interval, in effect saying, for example, "Give me a nudge every 10 seconds." Windows then sends your program recurrent WM_TIMER messages to signal the intervals.
At first, the Windows timer might seem a less important input device than the keyboard and mouse, and certainly it is for many applications. But the timer is more useful than you may think, and not only for programs that display time, such as the Windows clock that appears in the taskbar and the two clock programs in this chapter. Here are some other uses for the Windows timer, some perhaps not so obvious:
- Multitasking Although Windows 98 is a preemptive multitasking environment, sometimes it is more efficient for a program to return control to Windows as quickly as possible after processing a message. If a program must do a large amount of processing, it can divide the job into smaller pieces and process each piece upon receipt of a WM_TIMER message. (I'll have more to say on this subject in Chapter 20.)
- Maintaining an updated status report A program can use the timer to display "real-time" updates of continuously changing information, such as a display of system resources or the progress of a certain task.
- Implementing an "autosave" feature The timer can prompt a Windows program to save a user's work to disk whenever a specified period of time has elapsed.
- Terminating "demo" versions of programs Some demonstration versions of programs are designed to terminate, say, 30 minutes after they begin. The timer can signal such applications when the time is up.
- Pacing movement Graphical objects in a game or successive displays in a computer-assisted instruction program might need to proceed at a set rate. Using the timer eliminates the inconsistencies that might result from variations in microprocessor speed.
- Multimedia Programs that play CD audio, sound, or music often let the audio data play in the background. A program can use the timer to periodically determine how much of the audio has played and to coordinate on-screen visual information.
Another way to think of the timer is as a guarantee that a program can regain control sometime in the future after exiting the window procedure. Usually a program can't know when the next message is coming.