/**/ /*TimerThread (WIN32) free version 1.2 for WIN2000Compiled by: BC++ 5(free tool); C++ BUILDER 4, 5, 6, X; VC++ 5, 6, 7, 8; GCC;Writer: llbird Mail : wushaojian@21cn.com Blog : http://blog.csdn.net/wujian53Copyright(c) 2004.5 - 2006.1 */ #if (_WIN32_WINDOWS < 0x0500) #error the code need _WIN32_WINDOWS >= 0x0500 #endif #ifndef _TIMER_THREAD_H_ #define _TIMER_THREAD_H_ #include < objbase.h > #include < winbase.h > #include < windows.h > #include < process.h > class TimerThread ... {public: TimerThread(int nPriority = THREAD_PRIORITY_NORMAL) ...{ _TerminateEvent = CreateEvent(0, TRUE, FALSE, NULL); _TimerHandle = CreateWaitableTimer(NULL, FALSE, NULL); ::InitializeCriticalSection(&_Mutex); #ifdef _MT unsigned int id; _hHandle = (HANDLE)_beginthreadex(NULL, 0, StaticThreadProc, this, 0, &id); #else DWORD id; _hHandle = ::CreateThread(NULL, 0, StaticThreadProc, this, 0, &id); #endif _ThreadID = id; if(_hHandle != NULL) SetThreadPriority(_hHandle, nPriority); else MessageBox(NULL, "Create thread fail!", "TimerThread", MB_OK); } virtual ~TimerThread() ...{ Terminate(); CloseHandle(_hHandle); CloseHandle(_TimerHandle); CloseHandle(_TerminateEvent); ::DeleteCriticalSection(&_Mutex); } bool SetTimer(LONG lPeriodTime)//ms ...{ _lPeriodTime = lPeriodTime; LARGE_INTEGER li; memset(&li, 0, sizeof(LARGE_INTEGER)); return SetWaitableTimer(_TimerHandle, &li, _lPeriodTime, NULL, NULL, FALSE)!=0; } void Terminate() ...{ SetEvent(_TerminateEvent); if(WaitForSingleObject(_hHandle, 200) != WAIT_OBJECT_0) TerminateThread(_hHandle, 0); } operator HANDLE() ...{ return _hHandle; } HANDLE GetHandle() ...{ return _hHandle; } /**////关联消息的窗口句柄 inline void SetWnd(HWND hWnd) ...{ assert(::IsWindow(hWnd)); _hNotifyWnd = hWnd; } LONG GetFinishedCount() ...{ return _TimerHandleCount; } struct InnerLock ...{ TimerThread* ptr; InnerLock(TimerThread* p) : ptr(p) ...{ ptr->Lock(); } ~InnerLock() ...{ ptr->Unlock(); } }; /**////锁定资源 void Lock() ...{ ::EnterCriticalSection(&_Mutex); } void Unlock() ...{ ::LeaveCriticalSection(&_Mutex); }protected: HANDLE _TerminateEvent; HANDLE _TimerHandle; HANDLE _hHandle; unsigned _ThreadID; HWND _hNotifyWnd; /**/// 通知窗口 LONG _TimerHandleCount; LONG _lPeriodTime; CRITICAL_SECTION _Mutex; //初始化 virtual void OnInit() ...{ } //定时器函数 virtual void OnTimer()=0; //退出 virtual void OnExit() ...{ } virtual void Run() ...{ HANDLE HandleArray[2]; HandleArray[0] = _TimerHandle; HandleArray[1] = _TerminateEvent; for(;;) ...{ DWORD ret = WaitForMultipleObjects(2, HandleArray, false, INFINITE); if(ret == WAIT_OBJECT_0 + 1) break; if(ret == WAIT_OBJECT_0) ...{ try ...{ OnTimer(); } catch (...) ...{ } InterlockedIncrement(&_TimerHandleCount); } } } #ifdef _MT static UINT APIENTRY StaticThreadProc(LPVOID lpPara) //允许C多线程运行库 #else static DWORD WINAPI StaticThreadProc(LPVOID lpPara) #endif ...{ TimerThread *pObj = (TimerThread*)lpPara; pObj->OnInit(); pObj->Run(); pObj->OnExit(); #ifdef _MT _endthreadex(0); #endif return 0; }} ; #endif _TIMER_THREAD_H_