Windows多媒体定时器(精确到1ms) (二)

来源:互联网 发布:韩顺平javascript 编辑:程序博客网 时间:2024/05/16 06:14

这里还是聊的是 Windows多媒体定时器。 之前做的那个。感觉哪儿不对劲儿: 头文件封装没有做好, 回调函数没有写好。

今天,看了一个已经投入使用 的定时器(用示波器测试过,精确到1ms)。废话不多多说了。上代码:

------------------------- 我是分割线  ------------------------------------------------------

timer.h

////////////////////////////////////////////////////////////////////////////////////Timer.h: interface for the CTimer class.////      ////////////////////////////////////////////////////////////////////////////////多媒体计时器,用于最低间隔至5ms,误差不大于1ms的高精度计时//CPU占用极低,可忽略不计#if !defined(AFX_TIMER_H__263E5861_FE82_11D3_A4A2_5A5A5A5A5A5A__INCLUDED_)#define AFX_TIMER_H__263E5861_FE82_11D3_A4A2_5A5A5A5A5A5A__INCLUDED_#if _MSC_VER >= 1000#pragma once#endif // _MSC_VER >= 1000typedef BOOL (*TIMERCALLBACK)(DWORD); class CTimer  {public:CTimer();virtual ~CTimer();    BOOL Create (UINT nPeriod, UINT nRes, DWORD dwUser,  TIMERCALLBACK pfnCallback);protected:    static void CALLBACK TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2);    TIMERCALLBACK m_pfnCallback;    DWORD m_dwUser;    UINT m_nPeriod;    UINT m_nRes;    UINT m_nIDTimer;};#endif // !defined(AFX_TIMER_H__263E5861_FE82_11D3_A4A2_5A5A5A5A5A5A__INCLUDED_)

timer.cpp

// Timer.cpp: implementation of the CTimer class.////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include <mmsystem.h>#include "timer.h"#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif#pragma comment(lib, "winmm.lib")//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CTimer::CTimer(){    m_nIDTimer = NULL;}CTimer::~CTimer(){    if (m_nIDTimer)    {        timeKillEvent (m_nIDTimer);TRACE("多媒体定时器终止\n");    }}// CreateBOOL CTimer::Create (UINT nPeriod, UINT nRes, DWORD dwUser, TIMERCALLBACK pfnCallback){    ASSERT (pfnCallback);    ASSERT (nPeriod >= 5);    ASSERT (nPeriod >= nRes);    m_nPeriod = nPeriod;    m_nRes = nRes;    m_dwUser = dwUser;    m_pfnCallback = pfnCallback;    if ((m_nIDTimer = timeSetEvent (m_nPeriod, m_nRes, TimeProc, reinterpret_cast<DWORD>(this), TIME_PERIODIC)) == NULL)    {        return FALSE;    }TRACE("多媒体定时器启动\n");    return TRUE;}// Timer proc for multimedia timer callback set with timeSetTime().//// Calls procedure specified when Timer object was created. The // dwUser parameter contains "this" pointer for associated Timer object.// void CALLBACK CTimer::TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2){    // dwUser contains ptr to Timer objectCTimer * pRecvTimer = reinterpret_cast<CTimer *>(dwUser);    // Call user-specified callback and pass back user specified data    (pRecvTimer->m_pfnCallback) (pRecvTimer->m_dwUser);}


1 0
原创粉丝点击