在MFC中,我想引入定时器技术,请你举一个Demo 代码例子 说明我改如何做
时间: 2024-10-25 19:03:39 浏览: 6
在MFC(Microsoft Foundation Class)中,定时器技术可以通过使用`SetTimer`函数来设置一个定时器,并重载`OnTimer`函数来处理定时器事件。下面是一个简单的示例代码,演示如何在MFC应用程序中使用定时器:
```cpp
// MyApp.h : main header file for the application
#pragma once
#ifndef __MYAPP_H__
#define __MYAPP_H__
#include "resource.h"
#include "MyAppDlg.h"
class CMyApp : public CWinApp
{
public:
CMyApp();
virtual BOOL InitInstance();
};
class CMyAppDlg : public CDialogEx
{
public:
CMyAppDlg(CWnd* pParent = nullptr);
virtual ~CMyAppDlg();
protected:
virtual void DoDataExchange(CDataExchange* pDX);
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
private:
int m_nTimerID; // 定时器ID
UINT_PTR m_nElapsed; // 记录经过的时间
public:
afx_msg void OnTimer(UINT_PTR nIDEvent); // 定时器消息处理函数
};
#endif // __MYAPP_H__
```
```cpp
// MyApp.cpp : Defines the class behaviors for the application.
#include "stdafx.h"
#include "MyApp.h"
#include "MyAppDlg.h"
#include "afxdialogex.h"
BEGIN_MESSAGE_MAP(CMyAppDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_TIMER() // 添加定时器消息映射
END_MESSAGE_MAP()
CMyApp theApp;
CMyApp::CMyApp()
{
}
BOOL CMyApp::InitInstance()
{
CWinApp::InitInstance();
CMyAppDlg dlg;
m_pMainWnd = &dlg;
dlg.DoModal();
return FALSE;
}
CMyAppDlg::CMyAppDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_MYAPP_DIALOG, pParent), m_nTimerID(1), m_nElapsed(0)
{
}
CMyAppDlg::~CMyAppDlg()
{
KillTimer(m_nTimerID); // 销毁定时器
}
void CMyAppDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BOOL CMyAppDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
SetTimer(m_nTimerID, 1000, NULL); // 设置定时器,每秒触发一次
return TRUE;
}
void CMyAppDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
void CMyAppDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect
阅读全文