怎樣使用多媒體定時器

SetTimer定時的分辨率最小到50ms,在需要更小的定時間隔時他就無能爲力了,多媒體定時器在精確定實時中很有用處,能夠定時到一毫秒,不過得到這樣的好處是要付出代價的,使用起來略嫌麻煩,下面1-6步就是使用方法,不對之處請指正。

原來寫時使用了使用了英文註釋,比較簡單就不改了。
1.Link winmm.lib
 #i nclude <mmsystem.h>         
 #pragma comment(lib, "winmm.lib")
2.Define variables
 #define TARGET_RESOLUTION 1    // 1-millisecond target resolution
 int wTimerID;                      // store timer ID
 int msInterval;                      // delay
 UINT wTimerRes;                    // end resolution   
3.Obtaining and setting timer resolution
 //Obtaining timer resolution
 TIMECAPS tc;
 if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR)
 {
     MessageBox("Obtaining timer resolution error");
     return;
 }
 wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
    
  //setting timer resolution
 timeBeginPeriod(wTimerRes);     
4.Starting a Single/Periodic Timer Event
wTimerID=timeSetEvent(
    msInterval,                // delay
    wTimerRes,                 // resolution
    MMTimerProc,               // callback function
    (DWORD)UserData,// User Data, it is sent to dwUser of the callback function //parameter
    TIME_PERIODIC              // TIME_PERIODIC or TIME_ONESHOT
    );               
5.Writing a Timer Callback Function
 
 void CALLBACK MMTimerProc(UINT wTimerID, UINT msg,
    DWORD dwUser, DWORD dw1, DWORD dw2)
 {
    //timer routine
 }
6.Canceling a Timer Event
 
 if(wTimerID)  // is timer event pending?
 {             
     timeKillEvent(npSeq->wTimerID); // cancel the event
     wTimerID = 0;
 }
 
 
7.Error Shoting
1.DWORD dwUserData = (DWORD)this; //UserData
//if it is used in global area will get the following error
 
error C2355: 'this' : can only be referenced inside non-static member functions
 
2. int msInterval;
msInterval = 1;
 
//if it is used in global area will get the following error
 
error C2501: 'msInterval' : missing storage-class or type specifiers
error C2374: 'msInterval' : redefinition; multiple initialization
 
8.Unserstanding Difficult Points
1. wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章