[kaze's test] プログラミングメモ →目次


セットタイマーイベント timeSetEvent()

winmm.libtimeSetEvent()APIで、周期的にコールバック関数を呼び出すことができます。

MMRESULT timeSetEvent(
    UINT uDelay, 
    UINT uResolution, 
    LPTIMECALLBACK lpTimeProc, 
    DWORD dwUser, 
    UINT fuEvent 
    );

uDelayは、タイマーの遅延時間(ミリ秒)です。
uResolutionは、タイマーの精度で、小さくすると、精度が上がると同時に、CPUに掛ける負荷も重くなります。

コールバック関数は、下記のように宣言されています。
typedef void (CALLBACK TIMECALLBACK)(
                   UINT uTimerID, 
                   UINT uMsg, 
                   DWORD dwUser, 
                   DWORD dw1,     
                   DWORD dw2);


タイマーを停止、削除するには、下記の関数を呼び出します。
MMRESULT timeKillEvent(
    UINT uTimerID 
    );


#include "stdafx.h"
#include <windows.h>
#include <mmsystem.h>

#pragma comment(lib, "winmm.lib")

void CALLBACK timer_handle(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
{
    static int iCount = 0;
    printf("timer tick = %d\r\n", iCount++);
}

int main(int argc, char* argv[])
{
    MMRESULT uTimerID = timeSetEvent(500, 10, (LPTIMECALLBACK)timer_handle, (DWORD)NULL, TIME_PERIODIC);

    for (int i = 0; i < 10; i ++)
    {
        Sleep(1000);    
    }
    timeKillEvent(uTimerID);
    return 0;
}