现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

在线程里面使用SetTimer定时器

2012-11-30 21:24 工业·编程 ⁄ 共 2030字 ⁄ 字号 暂无评论

// 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);
}

》》》学习C++从入门到精通的经典书籍(修正版)

给我留言

留言无头像?