MFC - 定时器

日博365官网 ⌛ 2025-07-12 20:47:42 👤 admin 👁️ 9109 ❤️ 905
MFC - 定时器

❮ 上一节

下一节 ❯

MFC - 定时器

定时器 使用来自计算机或应用程序的重复时间间隔。 为了工作,每隔一段时间,控件就会向操作系统发送一条消息。 与大多数其他控件不同,MFC 定时器既没有代表它的按钮,也没有类。 要创建定时器,只需调用 CWnd::SetTimer() 方法即可。 此函数调用为您的应用程序创建一个定时器。 与其他控件一样,定时器使用标识符。

让我们创建一个新的基于 MFC 对话框的应用程序。

步骤 1 − 删除标题并将其 ID 设置为 IDC_STATIC_TXT

步骤 2 − 添加文本控件的值变量。

步骤 3 − 转到解决方案中的类视图。

步骤 4 − 单击 CMFCTimeDlg 类。

步骤 5 − 在"属性"窗口中,单击"消息"按钮。

步骤 6 − 单击 WM_TIMER 字段,然后单击其组合框的箭头。 选择添加 OnTimer 并实现该事件。

void CMFCTimerDlg::OnTimer(UINT_PTR nIDEvent) {

// TODO: Add your message handler code here and/or call default

CTime CurrentTime = CTime::GetCurrentTime();

int iHours = CurrentTime.GetHour();

int iMinutes = CurrentTime.GetMinute();

int iSeconds = CurrentTime.GetSecond();

CString strHours, strMinutes, strSeconds;

if (iHours < 10)

strHours.Format(_T("0%d"), iHours);

else

strHours.Format(_T("%d"), iHours);

if (iMinutes < 10)

strMinutes.Format(_T("0%d"), iMinutes);

else

strMinutes.Format(_T("%d"), iMinutes);

if (iSeconds < 10)

strSeconds.Format(_T("0%d"), iSeconds);

else

strSeconds.Format(_T("%d"), iSeconds);

m_strTimer.Format(_T("%s:%s:%s"), strHours, strMinutes, strSeconds);

UpdateData(FALSE);

CDialogEx::OnTimer(nIDEvent);

}

步骤 7 − 当上面的代码被编译并执行时,您将看到以下输出。

❮ mfc_windows_controls.html

❮ 上一节

下一节 ❯

相关文章

友情链接