2010年1月23日 星期六

TuWinTimer - creates a timer with the specified time-out value.

// creates a timer with the specified time-out value.



class CuMyClass
{
    TuWinTimer<CuMyClass> m_winTimer;

public:

    void OnMyFunction(void);
    void Init(void);

};

void CuMyClass::Init()
{
    m_winTimer.Init(1000); 
    m_winTimer.CombineElement(this, &CuMyClass::OnMyFunction, g_hWnd);

    ...
    m_winTimer.OnStardTime();
}

void CuMyClass::OnMyFunction(void)
{
    ...
    m_winTimer.OnStopTime();
}


// TuWinTimer.h

template <typename T>
class TuWinTimer 
    
    UINT m_uElapse;

    T *m_pElement;

    HWND m_hWnd;

    typedef void ( T::*ELEMENTTIME_TIMEOUTPROC)(void);
    ELEMENTTIME_TIMEOUTPROC m_fpTimeOutProc;


    static VOID CALLBACK TuWinTimerTimerProc( HWND hwnd,
        UINT uMsg,
        UINT_PTR idEvent,
        DWORD dwTime
    )
    {

        TuWinTimer<T> *pElement = (TuWinTimer<T>*)idEvent;
        T *pActiveElement = pElement->m_pElement;
        (pActiveElement->*(pElement->m_fpTimeOutProc))();

    }
public:
    
    TuWinTimer();
    ~TuWinTimer();

    void Init(UINT uElapse);
    void CombineElement(T *pElement, ELEMENTTIME_TIMEOUTPROC fpTimeOutProc, HWND hWnd);

    void OnStardTime();
    void OnStopTime();

};




template <typename T>
TuWinTimer<T>::TuWinTimer()
:m_uElapse(0)
,m_pElement(NULL)
,m_fpTimeOutProc(NULL)
,m_hWnd(NULL)
{
}

template <typename T>
TuWinTimer<T>::~TuWinTimer()
{
    OnStopTime();
}

template <typename T>
void TuWinTimer<T>::Init(UINT uElapse)
{
    m_uElapse = uElapse;
}

template <typename T>
void TuWinTimer<T>::OnStardTime()
{

    OnStopTime();
    ::SetTimer(m_hWnd, (UINT)this, m_uElapse, TuWinTimer<T>::TuWinTimerTimerProc );

}
template <typename T>
void TuWinTimer<T>::OnStopTime()
{
    ::KillTimer(m_hWnd, (UINT)this);
}


template <typename T>
void TuWinTimer<T>::CombineElement(T *pElement, ELEMENTTIME_TIMEOUTPROC fpTimeOutProc, HWND hWnd)
{ 
    m_pElement = pElement; 
    m_fpTimeOutProc = fpTimeOutProc;

    Assert( hWnd != NULL , L"Error : hWnd == NULL");
    m_hWnd = hWnd;
}

1 則留言:

  1. 後來發現, 獨立計時雖然不錯用, 但同步時很麻煩! 而且花時間做WM_TIMER 沒意思丫! 他的解析度不夠低!

    回覆刪除