Here we use the progress bar as an example to use the MFC timer.
Use the settimer function to create a timer
First look at an instance, start the timer, and define the timer ID in the class structure:
class CDlgOncloseDlg : public CDialogEx{// Constructionpublic:CDlgOncloseDlg(CWnd* pParent = NULL);// standard constructor// Dialog Dataenum { IDD = IDD_DLGONCLOSE_DIALOG }; enum { ID_TIMER_1 = 100, ID_TIMER_2 = 101, };
Then you need to start each timer in sequence:
BOOL CDlgOncloseDlg::OnInitDialog(){CDialogEx::OnInitDialog();// Add "About..." menu item to system menu.// TODO: Add extra initialization here this->SetTimer(ID_TIMER_1, 5000, NULL);
Then rewrite ontimer, which is written in the ontimer function as follows:
void CDlgOncloseDlg::OnTimer(UINT_PTR nIDEvent){ // TODO: Add your message handler code here and/or call default switch(nIDEvent) { default: break; case ID_TIMER_1: PostMessage(WM_CLOSE); break; } CDialogEx::OnTimer(nIDEvent);}
Settimer function usage
1) function prototype and Deformation
Creates a timer event. UINT SetTimer( UINT nIDEvent, UINT nElapse, void ( CALLBACK* lpfnTimer )(HWND, UINT, UINT, DWORD) = NULL ) throw();
Note: When setting the second parameter, you should note that if the set wait time is shorter than the processing time, the program will have a problem.
2) The function generation method is in classwizard. Select the class that requires a timer and add the wm_time message ing to automatically generate the ontime function. Then add the code to the function to implement the function.
It is automatically executed every other time.
3) callback function Format
Void callback timerproc (hwnd, uint nmsg, uint ntimerid, DWORD dwtime );
Killtimer
After the timer is canceled and no longer used, we should call killtimer to cancel the timer.
Destroys a timer event created by CWindow::SetTimer. BOOL KillTimer( UINT nIDEvent ) throw();
Timer instance to operate a progress bar Control
Add a progress bar and count in the class:
CProgressCtrl m_Process; int count;
Then, initialize the range and step value:
this->SetTimer(ID_TIMER_1, 1000, NULL); m_Process.SetRange(0, 100); m_Process.SetStep(10); count = 0;
Then modify the timer processing function:
void CDlgOncloseDlg::OnTimer(UINT_PTR nIDEvent){ // TODO: Add your message handler code here and/or call default switch(nIDEvent) { default: break; case ID_TIMER_1: //PostMessage(WM_CLOSE); count++; TRACE("count is %d", count); m_Process.StepIt(); int pos = m_Process.GetPos(); if(pos >= 100) { PostMessage(WM_CLOSE); } break; } CDialogEx::OnTimer(nIDEvent);}
That is to say, after 10 s, the progress bar is full. OK. Close the dialog box.