Vous êtes sur la page 1sur 2

Using Timers

This topic shows how to create and destroy timers, and how to use a timer to tra p mouse input at specified intervals. This topic contains the following sections. Creating a Timer The following example uses the SetTimer function to create two timers. The first timer is set for every 10 seconds, the second for every five minutes.

// Set two timers. SetTimer(hwnd, IDT_TIMER1, 10000, (TIMERPROC) NULL); SetTimer(hwnd, IDT_TIMER2, 300000, (TIMERPROC) NULL); // // // // // // // // handle to main window timer identifier 10-second interval no timer callback handle to main window timer identifier five-minute interval no timer callback

To process the WM_TIMER messages generated by these timers, add a WM_TIMER case statement to the window procedure for the hwnd parameter.

The calling convention for MyTimerProc must be based on the TimerProc callback f unction. If your application creates a timer without specifying a window handle, your app lication must monitor the message queue for WM_TIMER messages and dispatch them to the appropriate window.

Copy

HWND hwndTimer; MSG msg;

// handle to window for timer messages // message structure

while (GetMessage(&msg, // message structure NULL, // handle to window to receive the message

0, 0)) {

// lowest message to examine // highest message to examine

// Post WM_TIMER messages to the hwndTimer procedure. if (msg.message == WM_TIMER) { msg.hwnd = hwndTimer; } TranslateMessage(&msg); // translates virtual-key codes DispatchMessage(&msg); // dispatches message to window }

Destroying a Timer Applications should use the KillTimer function to destroy timers that are no lon ger necessary. The following example destroys the timers identified by the const ants IDT_TIMER1, IDT_TIMER2, and IDT_TIMER3.

Copy

// Destroy the timers. KillTimer(hwnd, IDT_TIMER1); KillTimer(hwnd, IDT_TIMER2); KillTimer(hwnd, IDT_TIMER3);

Using Timer Functions to Trap Mouse Input Sometimes it is necessary to prevent more input while you have a mouse pointer o n the screen. One way to accomplish this is to create a special routine that tra ps mouse input until a specific event occurs. Many developers refer to this rout ine as "building a mousetrap." The following example uses the SetTimer and KillTimer functions to trap mouse in put. SetTimer creates a timer that sends a WM_TIMER message every 10 seconds. Ea ch time the application receives a WM_TIMER message, it records the mouse pointe r location. If the current location is the same as the previous location and the application's main window is minimized, the application moves the mouse pointer to the icon. When the application closes, KillTimer stops the timer.

Vous aimerez peut-être aussi