为什么下面这段程序中不能执行回调函数,只停留在主函数中?
#include "stdafx.h"
#include <Mmsystem.h>
#pragma comment(lib, "winmm.lib") MMRESULT wTimerID;
UINT g_uTimerRes_ms;
void PASCAL CallBackMilliSecondProc(UINT wTimerID, UINT msg,DWORD dwUser,DWORD dwl,DWORD dw2);void main()
{
g_uTimerRes_ms=5000;//定时间隔为50ms
    wTimerID=timeSetEvent(g_uTimerRes_ms, 1, (LPTIMECALLBACK) CallBackMilliSecondProc, (DWORD)0, TIME_PERIODIC);   }void PASCAL CallBackMilliSecondProc(UINT wTimerID,UINT msg,DWORD dwUser,DWORD dwl,DWORD dw2) 
{
、、、、、、
            
 }

解决方案 »

  1.   

    主函数停止运行了,但定时器还没到点吧,试下这样修改
    void main()
    {
    g_uTimerRes_ms=5000;//定时间隔为50ms
      wTimerID=timeSetEvent(g_uTimerRes_ms, 1, (LPTIMECALLBACK) CallBackMilliSecondProc, (DWORD)0, TIME_PERIODIC);   
    while(TRUE)
       Sleep(500);
    }
      

  2.   

    sleep()的精度是50ms,而我实际中要求的精度是20ms。我的回调函数是完成串口数据的采集,因此要求每隔20ms执行一次回调函数,并在回调函数中完成串口数据的采集。我的程序不用对话框中的按钮,这种情况下如何激活回调函数呢?
      

  3.   

    使用事件对象,会大幅度提高timeSetEvent()的调用精度,参见msdn的说明:
    MMRESULT timeSetEvent(
      UINT           uDelay,      
      UINT           uResolution, 
      LPTIMECALLBACK lpTimeProc,  
      DWORD_PTR      dwUser,      
      UINT           fuEvent      
    );
    ...
     If fuEvent specifies the TIME_CALLBACK_EVENT_SET or TIME_CALLBACK_EVENT_PULSE flag, then the lpTimeProc parameter is interpreted as a handle to an event object. The event will be set or pulsed upon completion of a single event or periodically upon completion of periodic events. 
      

  4.   

    3.MMRESULT   timeKillEvent(UINT   uTimerID)     
        该函数取消一个指定的定时器回调事件。uTimerID标识要取消的事件(由timeSetEvent函数返回的标识符)。如果成功则返回TIMERR_NOERROR,如果定时器时间不存在则返回MMSYSERR_INVALPARAM。     4.回调函数
        void   CALLBACK   TimeProc(     
        UINT   uID,     
        UINT   uMsg,     
        DWORD   dwUser,     
        DWORD   dw1,     
        DWORD   dw2);     
        
        该函数是一个应用程序定义的回调函数,出现定时器事件时该函数被调用。TimeProc是应用程序定义的函数名的占位符。使用该函数   
      时要注意的是,它只能调用以下有限的几组API函数:PostMessage,timeGetSystemTime,   timeGetTime,   timeSetEvent,timeKillEvent   
      ,midiOutShortMsg,   midiOutLongMsg,OutputDebugString。同时也不要使用完成时间很长的API函数,程序尽可能简短。