在线程里面使用SetTimer定时器

来源:互联网 发布:淘宝网址微信转换 编辑:程序博客网 时间:2024/06/05 17:51

// MyThreadTimer.h

#pragma once 
class MyThreadTimer 
: public CWinThread 

DECLARE_MESSAGE_MAP() 
public: 
        MyThreadTimer(void); 
        ~MyThreadTimer(void); 
public: 
        bool start(int second); 
        void stop(); 
private: 
        virtual BOOL InitInstance(); 
        virtual int Run(); 
private: 
        virtual void onTimer(WPARAM wParam, LPARAM lParam); 
        virtual void onStartTimer(WPARAM wParam, LPARAM lParam); 
        virtual void onStopTimer(WPARAM wParam, LPARAM lParam); 
private: 
        UINT_PTR _timerID; 
};

// MyThreadTimer.cpp

#include "StdAfx.h" 
#include "MyThreadTimer.h" 
#define WM_MY_TIMER (WM_USER + 1) 
#define WM_MY_START_TIMER (WM_USER + 2) 
#define WM_MY_STOP_TIMER (WM_USER + 3) 
BEGIN_MESSAGE_MAP(MyThreadTimer, CWinThread) 
        ON_THREAD_MESSAGE(WM_MY_TIMER, MyThreadTimer::onTimer) 
        ON_THREAD_MESSAGE(WM_MY_START_TIMER, MyThreadTimer::onStartTimer) 
        ON_THREAD_MESSAGE(WM_MY_STOP_TIMER, MyThreadTimer::onStopTimer) 
END_MESSAGE_MAP() 
VOID CALLBACK timerFun(HWND wnd, UINT msg, UINT_PTR id, DWORD d) 

        DWORD threadID = GetCurrentThreadId(); 
        PostThreadMessage(threadID, WM_MY_TIMER, 0, 0); 

MyThreadTimer::MyThreadTimer(void) 
        :_timerID(NULL) 


MyThreadTimer::~MyThreadTimer(void) 


bool MyThreadTimer::start(int second) 

        if (m_hThread != NULL) 
        { 
                return false; 
        } 
        m_bAutoDelete = FALSE; 
        CreateThread(); 
        PostThreadMessage(WM_MY_START_TIMER, (WPARAM)second, 0); 
        return true; 

void MyThreadTimer::stop() 

        if (m_hThread == NULL) 
        { 
                return; 
        } 
        PostThreadMessage(WM_MY_STOP_TIMER, 0, 0); 
        PostThreadMessage(WM_QUIT, 0, 0);

        WaitForSingleObject(m_hThread, INFINITE); 

BOOL MyThreadTimer::InitInstance() 

        return TRUE; 

int MyThreadTimer::Run() 

        return CWinThread::Run(); 

void MyThreadTimer::onTimer(WPARAM wParam, LPARAM lParam) 

        AfxMessageBox(_T("定时器时间到了")); 

void MyThreadTimer::onStartTimer(WPARAM wParam, LPARAM lParam) 

        _timerID = SetTimer(NULL, 0, int(wParam) * 1000, timerFun); 

void MyThreadTimer::onStopTimer(WPARAM wParam, LPARAM lParam) 

        KillTimer(NULL, _timerID); 
}

原创粉丝点击