Three methods of timer (1)

Source: Internet
Author: User

You can use the settimer function to assign a timer to your windows program. settimer contains an unsigned integer parameter, which specifies the duration of the interval, in milliseconds.

This function sends a wm_timer message to your program at a specified interval;

The timer message is not asynchronous.

Because timers are interrupted Based on hardware timers, programmers are sometimes misled to think that their programs may be interrupted asynchronously and forced to process wm_timer messages. In fact, in Windows, wm_timer messages are similar to wm_paint messages. Both messages are of low priority and will be received only when there are no other messages in the message queue.

 

Three methods to use a timer:

Method 1:

# Define timer_sec 1 # define timer_min 2 // use two settimer functions to set two timers settimer (hwnd, timer_sec, 1000, null); settimer (hwnd, timer_min, 60000, null ); // The processing logic of wm_timer is as follows: Case wm_timer: Switch (wparam) {Case timer_sec: process once per second; break; Case timer_min: Process break once per minute;} return 0;

 

Let's take a look at a simple example. Within one second, we can change the background color of the customer area to make the system sound.

# Include <windows. h> # define id_timer 1 lresult callback windowproc (hwnd, // handle to window uint umsg, // message identifier wparam, // first message parameter lparam // second message parameter); int winapi winmain (hinstance, // handle to current instance hinstance hprevinstance, // handle to previous instance lpstr lpcmdline, // command line int ncmdshow // show state) {Static tchar szappname [] = text ("leidemingzi"); hwnd; MSG; wndclass. cbclsextra = 0; wndclass. cbwndextra = 0; wndclass. hbrbackground = (hbrush) getstockobject (white_brush); wndclass. hcursor = loadcursor (null, idc_arrow); wndclass. hicon = loadicon (null, idi_error); wndclass. hinstance = hinstance; wndclass. lpfnwndproc = windowproc; wndclass. lpszclassname = szappname; wndclass. lpszmenuname = NULL; wndclass. Style = cs_hredraw | cs_vredraw; If (! Registerclass (& wndclass) {MessageBox (null, text ("the program require window nt! "), Text (" Xiao Tips "), mb_iconerror); Return 0;} hwnd = createwindow (szappname, // registered Class Name text (" this is Title "), // window name ws_overlappedwindow, // window style cw_usedefault, // horizontal position of window cw_usedefault, // vertical position of window cw_usedefault, // window width cw_usedefault, // window height null, // handle to parent or owner window null, // menu handle or Chi LD identifier hinstance, // handle to application instance null // window-creation data); showwindow (hwnd, ncmdshow); updatewindow (hwnd); While (getmessage (& MSG, null, 0, 0) {translatemessage (& MSG); dispatchmessage (& MSG);} return MSG. wparam;} lresult callback windowproc (hwnd, // handle to window uint umsg, // message identifier wparam, // first message parameter lparam // second message P Arameter) {static bool fflipflop = false; hbrush; HDC; paintstruct pS; rect; Switch (umsg) {Case wm_create: settimer (hwnd, id_timer, 1000, null ); // set a timer with a return 0 interval of 1 second; Case wm_timer: messagebeep (mb_iconasterisk); // send the system sound fflipflop =! Fflipflop; // obtain the inverse invalidaterect (hwnd, null, false); // trigger the wm_paint event return 0; Case wm_paint: HDC = beginpaint (hwnd, & PS); getclientrect (hwnd, & rect); // obtain the size of the customer zone hbrush = createsolidbrush (fflipflop? RGB (255, 0): RGB (,); // determines whether to fill in red or blue fillrect (HDC, & rect, hbrush); endpaint (hwnd, & PS ); deleteobject (hbrush); // Delete the painter return 0; Case wm_destroy: killtimer (hwnd, id_timer); // Delete postquitmessage (0); Return 0 ;} return defwindowproc (hwnd, umsg, wparam, lparam );}

Although the program is small, "five dirty" tasks.

 

Method 2:

So that you can only send the timer message to another function in the program in windows.

The function that receives the timer message is called a "Callback" function. This is a function called by windows in the program. You can tell the address of this function for Windows and it will be called after windows.

Settimer is not a Windows function that uses the callback function. createdialog and dialogbox both use the callback function to process messages in the dialog box. There are several Windows functions (enumchildwindow, enumfont, enumobject, enumprops, enumwindow) the enumeration information will be passed to the callback function. Several other uncommon functions, such as graystring, linedda, and setjavaswhookex, also require the callback function.

// We name the callback function timerproc (you can take other names and the function names do not overlap) void callback timerproc (hwnd, unit umsg, uint itimerid, DWORD dwtime) {processing timer messages}

 

Next let's take a look at the comparison between the second method and the first method. The functions are the same.

#include<windows.h>#define ID_TIMER 1LRESULT CALLBACK WindowProc(  HWND hwnd,      // handle to window  UINT uMsg,      // message identifier  WPARAM wParam,  // first message parameter  LPARAM lParam   // second message parameter);VOID CALLBACK TimerProc(  HWND hwnd,      // handle to window  UINT uMsg,      // message identifier  UINT iTimerID , // first message parameter  DWORD dwTime   // second message parameter);int WINAPI WinMain(  HINSTANCE hInstance,      // handle to current instance  HINSTANCE hPrevInstance,  // handle to previous instance  LPSTR lpCmdLine,          // command line  int nCmdShow              // show state){static TCHAR szAppName[]=TEXT("leidemingzi");HWND hwnd;MSG msg;WNDCLASS wndclass;wndclass.cbClsExtra=0;wndclass.cbWndExtra=0;wndclass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);wndclass.hCursor=LoadCursor(NULL,IDC_ARROW);wndclass.hIcon=LoadIcon(NULL,IDI_ERROR);wndclass.hInstance=hInstance;wndclass.lpfnWndProc=WindowProc;wndclass.lpszClassName=szAppName;wndclass.lpszMenuName=NULL;wndclass.style=CS_HREDRAW|CS_VREDRAW;if(!RegisterClass(&wndclass)){MessageBox(NULL,TEXT("the program require window nt!"),TEXT("xiao tips"),MB_ICONERROR);return 0;}hwnd=CreateWindow(  szAppName,  // registered class name  TEXT("this is title"), // window name  WS_OVERLAPPEDWINDOW,        // window style  CW_USEDEFAULT,                // horizontal position of window  CW_USEDEFAULT,                // vertical position of window  CW_USEDEFAULT,           // window width  CW_USEDEFAULT,          // window height  NULL,      // handle to parent or owner window  NULL,          // menu handle or child identifier  hInstance,  // handle to application instance  NULL        // window-creation data);ShowWindow(hwnd,nCmdShow);UpdateWindow(hwnd);while(GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg);DispatchMessage(&msg);}return msg.wParam;}LRESULT CALLBACK WindowProc(  HWND hwnd,      // handle to window  UINT uMsg,      // message identifier  WPARAM wParam,  // first message parameter  LPARAM lParam   // second message parameter){switch(uMsg){case WM_CREATE:SetTimer(hwnd,ID_TIMER,1000,TimerProc);return 0;case WM_DESTROY:KillTimer(hwnd,ID_TIMER);PostQuitMessage(0);return 0;}return DefWindowProc(hwnd,uMsg,wParam,lParam);}VOID CALLBACK TimerProc(  HWND hwnd,      // handle to window  UINT uMsg,      // message identifier  UINT iTimerID,  // first message parameter  DWORD dwTime   // second message parameter){static BOOL fFlipFlop=FALSE;HBRUSH hbrush;HDC hdc;RECT rect;MessageBeep(MB_ICONASTERISK);fFlipFlop=!fFlipFlop;GetClientRect(hwnd,&rect);hdc=GetDC(hwnd);hbrush=CreateSolidBrush(fFlipFlop?RGB(255,0,0):RGB(0,0,255));FillRect(hdc,&rect,hbrush);ReleaseDC(hwnd,hdc);DeleteObject(hbrush);}

Method 3:

The third method for timer setting is similar to the second method, except that the hwnd parameter of settimer is set to null and the second method is ignored. In addition, this function returns the timer ID.

itimerId=SetTimer(NULL,0,wMsecInterval,TimerProc);KillTimer(NULL,iTimerID);

This type of timer is rarely used. If you need to call settimer many times in different programs, but do not want to record which timer IDs have been used, this method may be useful.

Here, we will not give an example.

(Pay attention to the timer (x). There are more exciting examples)

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.