MFC中Edit控件显示系统时间

来源:互联网 发布:小米笔记本l 知乎 编辑:程序博客网 时间:2024/04/29 04:57

MFC中实时显示系统时间

 下面给出在基于对话框的MFC应用程序的Edit控件中实时显示系统时间的方法。首先来了解一下几个主要的与定时器有关的函数。 SetTimer()函数表示定义一个定时器。根据定义指定的窗口,在指定的窗口(CWnd)中实现OnTimer事件,这样,就可以响应事件了。SetTimer有两个函数。一个是全局的函数::SetTimer()  UINT SetTimer( HWND hWnd,     // handle of window for timer messages                          UINT nIDEvent, // timer identifier                          UINT uElapse,  // time-out value                          TIMERPROC lpTimerFunc // address of timer procedure                         );   其中hWnd 是指向CWnd的指针,即处理Timer事件的窗口类。说道窗口类(CWnd) 我们有必要来看一下CWnd的继承情况:CWnd有以下子类:CFrameWnd,CDialog,CView,CControlBar等类 这也意味这些类中都可以定义SetTimer事件。 SetTimer()的另外一种定义为: UINT SetTimer( UINT nIDEvent, UINT nElapse, void (CALLBACK EXPORT* lpfnTimer)(HWND, UINT, UINT, DWORD) );  nIDEvent:是指设置这个定时器的iD,即身份标志,这样在OnTimer()事件中,才能根据不同的定时器,来做不同的事件响应 这个ID是一个无符号的整型。 nElapse:是指时间延迟。单位是毫秒。这意味着,每隔nElapse毫秒系统调用一次Ontimer()。  void (CALLBACK EXPORT* lpfnTimer) (HWND, UINT, UINT, DWORD): Specifies the address of the application-supplied TimerProc callback function that processes the WM_TIMER messages. If this parameter is NULL, the WM_TIMER messages are placed in the application’s message queue and handled by the CWnd object。 意思指:指定应用程序提供的TimerProc回调函数的地址,来处里这个WM_TIMER 事件。 如果是NULL,则由定义这个Timer事件的CWnd对象来处理该Timer事件。它将WM_TIMER消息传递给这个对象 通过实现这个对象的OnTimer()事件来处理这个Timer事件。所以,一般情况下,我们将这个值设为NULL 由设置该定时器的对象中的OnTimer()函数来处理这个事件。对于SetTimer()可以在初始化当中添加! OnTimer()函数是响应用SetTimer()函数设定的时钟发送的时钟消息的,你没设定时钟,就不会有时钟消息 OnTimer()里的语句当然也不会被调用。为类添加WM_TIMER消息响应,会看到类中出现OnTimer(UINT nIDEvent)函数。  KillTimer()同SetTimer()一样,它也有两个,一个是全局的::KillTimer(),另一个是CWnd的一个函数。声明如下: //全局函数 BOOL KillTimer( HWND hWnd, // handle of window that installed timer                          UINT uIDEvent // timer identifier                         );  //CWnd函数 BOOL KillTimer( int nIDEvent );  这两个函数表示的意思是将ID为nIDEVENT的定时器移走,使其不再作用。其用法如同SetTimer()一样 一般将KillTimer()语句放在需要移去定时器的地方或程序退出是的窗口销毁过程中。 在基于对话框的MFC应用程序中,添加一个Edit控件,ID标号为IDC_EDIT_TIME。 在OnInitDialog()函数中添加下面语句: SetTimer(1,1000,NULL);//1000毫秒发生一次定时器事件 为类添加WM_TIMER消息响应函数OnTimer(UINT_PTR nIDEvent): void CTestDlg::OnTimer(UINT_PTR nIDEvent) {    // TODO: Add your message handler code here and/or call default   CDialog::OnTimer(nIDEvent);   CString str;   CTime   theTime   =   CTime::GetCurrentTime();    str.Format("%02d:%02d:%02d",theTime.GetHour(),theTime.GetMinute(),theTime.GetSecond());   SetDlgItemText(IDC_EDIT_TIME,str);  } 为类添加WM_DESTROY消息响应函数OnDestroy(): void CTestDlg::OnDestroy() {    CDialog::OnDestroy();    // TODO: Add your message handler code here    KillTimer(1); }
0 0
原创粉丝点击