MFC Timer定时器

知识点:
  定时器Timer
  创建定时器
  销毁定时器
  代码测试


一、  创建定时器 

UINT SetTimer(
  
HWND hWnd,             // 指定关联定时器的窗口句柄,在MFC版将省略此参数
  
UINT nIDEvent,           // 定时器ID  
UINT uElapse,             // 时间间隔  单位毫秒
  
TIMERPROC lpTimerFunc   //定时器回调函数地址

);

定时器回调函数格式

VOID CALLBACK TimerProc(
 
HWND hwnd,     // handle of window for timer messages
   
UINT uMsg,       // WM_TIMER message
  
UINT idEvent,     // timer identifier
  
DWORD dwTime   // current system time
);


二、  销毁定时器
BOOL KillTimer(
 
HWND hWnd,    // handle of window that installed timer
   在MFC版将省略此参数

UINT uIDEvent   // timer identifier

);

三、  代码测试
 //实时显示 当前时间  参考C语言053课
time_t t;
time(&t);
tm *TimeInfo=localtime(&t);
m_sTime.Format(L"%02d:%02d:%02d",TimeInfo->tm_hour,TimeInfo->tm_min,TimeInfo->tm_sec);




//代码
// CDialog_Timer 消息处理程序
void CALLBACK EXPORT TimerProc(
                               HWND hWnd,      // handle of CWnd that called SetTimer
                               UINT nMsg,      // WM_TIMER
                               UINT nIDEvent,   // timer identification
                               DWORD dwTime    // system time
                               )
{

    if (nIDEvent==myTimerID) //
    {
        //执行代码
        TRACE("my TimerProc %d
",dwTime);
        //显示当前时间
        time_t t;
        time(&t);
        tm *timeinfo=localtime(&t);
        TRACE("%02d:%02d:%02d",timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
     
    }
}


void CDialog_Timer::OnBnClickedButton1()
{
    // TODO: 在此添加控件通知处理程序代码
    //SetTimer(1001,1000,NULL);//WM_TIMER
    SetTimer(1001,1000,TimerProc);//不产生WM_TIMER
}

LRESULT CDialog_Timer::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
    // TODO: 在此添加专用代码和/或调用基类
  //if (message==WM_TIMER)
  //{
     // if (wParam==myTimerID) //
     // {
        //  //执行代码
        //  TRACE("1111111111
");
        //  //显示当前时间
        //  time_t t;
        //  time(&t);
        //  tm *timeinfo=localtime(&t);
        //  m_sTime.Format(L"%02d:%02d:%02d",timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
        //  UpdateData(false);
     // }

  //}
    return CDialog::WindowProc(message, wParam, lParam);
}

void CDialog_Timer::OnBnClickedButton2()
{
    // TODO: 在此添加控件通知处理程序代码
    KillTimer(myTimerID);//销毁定时器
}

void CDialog_Timer::OnTimer(UINT_PTR nIDEvent)
{
    // TODO: 在此添加消息处理程序代码和/或调用默认值
    if (nIDEvent==myTimerID) //
         {
          //执行代码
          TRACE("1111111111
");
          //显示当前时间
          time_t t;
          time(&t);
          tm *timeinfo=localtime(&t);
          m_sTime.Format(L"%02d:%02d:%02d",timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
          UpdateData(false);
         }
    CDialog::OnTimer(nIDEvent);
}
原文地址:https://www.cnblogs.com/whzym111/p/6229874.html