MFC's Timer OnTimer

Source: Internet
Author: User

This article summarizes the source from the chicken peck rice, thanks to the chicken peck rice. Source: http://www.jizhuomi.com/software/232.html

Timer INTRODUCTION

Timers that can help developers or users complete a task on a regular basis. When using the timer, we can pass the time interval data to the system, then the system will trigger the timer handler after each time interval, and realize the periodic automatic operation. For example, we can in the data acquisition system, the timer set timing acquisition time interval of 1 hours, then every 1 hours the system will collect data once, so that in the case of unmanned operation of the accurate operation.

MFC Timers

In VS2010 programming, we can implement the timer function using the member function SetTimer provided by the CWnd Class of MFC, or you can use the Windows API function SetTimer. The use of the two methods is actually very similar, but there are differences.

The SetTimer member function of a CWnd class can only be called in a CWnd class or its derived class, and the API function SetTimer does not have this restriction, which is an important difference. Because this tutorial is mainly about MFC programming, so here is the first emphasis on the use of MFC timer, about the use of API function SetTimer Chicken Peck rice will be on the basis of the MFC timer to explain the extension.

Chicken Peck Rice The following steps give the method of using the MFC timer.

1, start the timer.

Starting the timer requires using the CWnd class member function SetTimer. The prototype of Cwnd::settimer is as follows:

Uint_ptr SetTimer (
Uint_ptr Nidevent,
UINT Nelapse,
void (callback* Lpfntimer
) (HWND,
UINT,
Uint_ptr,
DWORD
)
);

The parameter nidevent specifies a non-zero timer ID, the parameter nelapse specifies the interval, in milliseconds, the parameter lpfntimer specifies the address of a callback function, and if the parameter is NULL, the WM_TIMER message is sent to the application's message queue. and is handled by the CWnd object. If this function succeeds then returns the ID of a new timer, we can use this ID to destroy the timer through the KillTimer member function and return 0 if the function fails.

With the SetTimer member function we can see that there are two ways to handle timed events, one is through the message response function of the WM_TIMER message, and one is through a callback function .

If you want to start multiple timers, call the SetTimer member function multiple times. In addition, in different CWnd can have the same ID timer, does not conflict.

2. Add a message handler for the WM_TIMER message, or define a callback function.

If the last argument is null when the Cwnd::settimer function is called, the timed event is handled through the WM_TIMER message handler function. The way to add a handler for a WM_TIMER message is to find the class to add the timer in the Class View class of the VS2010 project, right-click, select Properties, display its property page, and then click the Messages button on the Property Page toolbar. The following list lists all messages, finds the WM_TIMER message, and adds a message handler function. Once added, the CPP file will appear similar to the following:

C + + code
    1. Begin_message_map (Cexample44dlg, CDialogEx)
    2. ......
    3. On_wm_timer ()
    4. End_message_map ()
    5. void Cexample44dlg::ontimer (uint_ptr nidevent)
    6. {
    7. //Todo:add your message handler code here and/or call default
    8. Cdialogex::ontimer (nidevent);
    9. }

You can then do the appropriate processing in the OnTimer function. The OnTimer parameter nidevent is the timer ID, which is the timer ID specified in the SetTimer member function, and if there are multiple timers, we can handle it as follows:

C + + code
  1. void Cexample44dlg::ontimer (uint_ptr nidevent)
  2. {
  3. //Todo:add your message handler code here and/or call default
  4. switch (nidevent)
  5. {
  6. Case 1:
  7. //If you receive a message with a timer with ID 1, call the FUNC1 function
  8. Func1 ();
  9. Break ;
  10. Case 2:
  11. //If you receive a message with a timer with ID 2, call the FUNC2 function
  12. Fun2 ();
  13. Break ;
  14. ......
  15. Default:
  16. Break ;
  17. }
  18. Cdialogex::ontimer (nidevent);
  19. }

If the last parameter is not NULL when you call the Cwnd::settimer function, you need to define a callback function. The callback function is in the following form:

C + + code
    1. void callback export timerproc (   
    2.   
    3. hwnd hwnd, // HANDLE OF CWND THAT CALLED SETTIMER   
    4.   
    5. uint nmsg,  // wm_timer   
    6.   
    7. uint nidevent // timer  identification   
    8.   
    9. dword dwtime // system time    
    10.   

The parameter HWND is the handle to the CWnd object that invokes the SetTimer member function, which is the handle to the window that owns the timer, the parameter nmsg is Wm_timer, and is always wm_timer; parameter nidevent is the timer ID The parameter dwtime is the number of milliseconds since the system started, that is, the return value of the GetTickCount function.

So the last parameter of the Cwnd::settimer function can be timerproc.

Note here that the name of the callback function is not necessarily timerproc and can take other names, but the return value type, the type and number of parameters cannot be changed.

Chicken Peck Rice gives an example of a callback function:

C + + code
  1. void CALLBACK EXPORT Timerproc (hwnd hwnd,UINT nmsg,uint Ntimerid,DWORD dwtime)
  2. {
  3. switch (ntimerid)
  4. {
  5. Case 1:
  6. //Handle event for timer with ID 1
  7. Func1 ();
  8. Break ;
  9. Case 2:
  10. //Handle event for timer with ID 2
  11. Func2 ();
  12. Break ;
  13. ......
  14. Default:
  15. Break ;
  16. }
  17. }

The callback function is a global function that needs to be written in front of the location where it is used, or written in the back and then declared before use.

3, destroy the timer.

When you no longer use the timer, you can destroy it. Destroying the timer requires the KillTimer member function of the CWnd class, and the Cwnd::killtimer function is prototyped as follows:

C + + code
    1. BOOL KillTimer (uint_ptr nidevent);

The parameter nidevent is the ID of the timer to be destroyed, which is the timer ID set when the Cwnd::settimer function is called. Returns true if the timer is destroyed, or false if the specified timer is not found.

If you want to destroy more than one timer, call the KillTimer function multiple times and pass in the ID of the timer to be destroyed, respectively.

using Timers with Windows API functions

If we do not use the MFC timer, and the use of the timer through the Windows API functions, it is actually very similar. Below the chicken Peck rice simple next step.

1, start the timer.

Using the API function SetTimer to start the timer, the SetTimer function is prototyped as follows:

C + + code
    1. uint_ptr settimer (          
    2.     hwnd    
    3.             hwnd,   
    4.     uint_ptr    
    5.             nidevent,   
    6.     uint    
    7.             uelapse,   
    8.     TIMERPROC    
    9.              lptimerfunc   
    10. );   

The parameter HWND is the handle of the window associated with the timer, the parameter nidevent is a non-zero timer ID, if the HWND equals NULL, and there is no timer with ID nidevent, then the nidevent parameter is ignored and a new ID timer is generated. If the HWND is not NULL and the specified window of HWND already has a timer with ID nidevent, the existing timer is replaced by the new timer. The parameters Uelapse and Lptimerfunc are the same as Cwnd::settimer functions.

2. Add a message handler for the WM_TIMER message, or define a callback function.

If the last parameter when calling the SetTimer function is null, we need to add the handler function for the WM_TIMER message, and note that the additional data for the WM_TIMER message wparam the timer Id,lparam as a pointer to the callback function. If the callback function is null when calling SetTimer, then LPARAM is also null.

And if the last argument is not NULL when calling the SetTimer function, we need to define the callback function. The callback function is defined with the MFC timer.

3, destroy the timer.

The destroy timer uses the KillTimer API function, which is prototyped as follows:

C + + code
    1. BOOL KillTimer (hwnd hwnd,uint_ptr uidevent);

The parameter HWND is the handle of the window associated with the timer, the same as the HWND parameter value of the SetTimer function when the timer is started, and the parameter uidevent is the ID of the timer to be destroyed, if the parameter hwnd passed to SetTimer is valid, The uidevent should be the same as the parameter nidevent passed to SetTimer, and if the SetTimer parameter hwnd is NULL, uidevent should be the timer ID returned by SetTimer. The function returns True if it succeeds, otherwise false is returned.

MFC Timer Application Example

Chicken Peck rice To show you the example of a timer, the example function is very simple, is to use two timers, update the display of two edit boxes, the first edit box refreshed once per second, from 1 to 10, and then destroy the timer, the second edit box is refreshed every two seconds, from 1 to 5, and then destroy the timer. The following simple steps:

1, create a dialog-based project, the name is set to "Example44".

2. In the automatically generated dialog template Idd_example44_dialog, delete "Todo:place dialog controls here." A static text control. Add two static TextBox controls, caption set to 1 seconds to refresh and 2 seconds to refresh, add two edit control controls, ID use default idc_edit1 and Idc_edit2, both of which have the read only property set to True. The dialog template at this point is as follows:

3. Add two member variables for the Cexample44dlg class, M_ndata1, M_ndata2, respectively, and initialize in the constructor of the Cexample44dlg class:

C + + code
    1. Cexample44dlg::cexample44dlg (cwnd* pparent /*=null*/)
    2. : CDialogEx (Cexample44dlg::idd, pparent)
    3. {
    4. M_hicon = AfxGetApp ()->loadicon (IDR_MAINFRAME);
    5. ///two data initialized to 0
    6. m_ndata1 = 0;
    7. M_NDATA2 = 0;
    8. }

4. Double-click the OK button on the dialog template, add the click Message Handler function, and modify the following:

C + + code
    1. void Cexample44dlg::onbnclickedok ()
    2. {
    3. //Todo:add your control notification handler code here
    4. //start timer with ID 1, timing time is 1 seconds
    5. SetTimer (1, +, NULL);
    6. //start timer with ID 2, timing time is 2 seconds
    7. SetTimer (2, +, NULL);
    8. //cdialogex::onok ();
    9. }

This way, when the OK button is clicked, it does not exit, but instead launches two timers.

5, according to the above MFC timer explanation for the WM_TIMER message Add processing function method, add Wm_timer Message handler function OnTimer, and modify its implementation as follows:

C + + code
  1. void Cexample44dlg::ontimer (uint_ptr nidevent)
  2. {
  3. //Todo:add your message handler code here and/or call default
  4. switch (nidevent)
  5. {
  6. Case 1:
  7. //If the M_NDATA1 has reached 10, destroy the timer with ID 1
  8. if (ten = = m_ndata1)
  9. {
  10. KillTimer (1);
  11. Break ;
  12. }
  13. //Refresh the display of the edit box idc_edit1
  14. Setdlgitemint (Idc_edit1, ++m_ndata1);
  15. Break ;
  16. Case 2:
  17. //If the M_NDATA2 has reached 5, destroy the timer with ID 2
  18. if (5 = = m_ndata2)
  19. {
  20. KillTimer (2);
  21. Break ;
  22. }
  23. //Refresh the display of the edit box Idc_edit2
  24. Setdlgitemint (Idc_edit2, ++M_NDATA2);
  25. Default:
  26. Break ;
  27. }
  28. Cdialogex::ontimer (nidevent);
  29. }

6, run the program, click the OK button to see the effect.

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

1. Define in class

afx_msg void OnTimer (UINT nidevent);

2. Add in CPP

Begin_message_map (Yujingdlg, CDialog)
On_wm_ctlcolor ()//Color message
On_wm_paint ()
On_wm_timer
On_bn_clicked (IDCANCEL, &yujingdlg::onbnclickedcancel)
End_message_map ()

3. Add in the initial session function or other button response

SetTimer (1,50,null); Timer 1,50ms Refresh once, use OnTimer function

4. Write OnTimer function

void Yujingdlg::ontimer (UINT nidevent)
{
th+=0.157;
if (th>6.28) th-=6.28;
Invalidate ();
InvalidateRect (CRect (0,0,500,500)); Refresh Area
Cdialog::ontimer (nidevent);
}

MFC's Timer OnTimer

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.