#pragma once #include <boost/thread.hpp> #include <boost/asio.hpp> #include <functional> /* 功能:延迟一段时间调用SendMessage发送Windows消息 测试环境: [1]VS2013 Sp3 [2]boost 1.56 使用方式: Step1:把CDelayEvent属性化为当前类成员。 Step2:在任意地方调用,例子如下 m_delayEvent.SendMessage(::SendMessage, GetSafeHwnd(), WM_MYUPDATEVIEW, 0, 0, 0); 可重复调用。 N次调用,会有N个事件等待执行。 Step3: 然后延迟一段时间后,SendMessage函数就会被调用。 */ namespace kagula { typedef std::function<long (const HWND hwnd, const UINT msg, const WPARAM wParam, const LPARAM lParam)> Callback; class CDelayEvent { public: CDelayEvent(); ~CDelayEvent(); void SendMessage(Callback callback, const HWND hwnd, const UINT msg, const WPARAM wParam=0, const LPARAM lParam=0, int millisecond=1000/30); private: boost::asio::io_service _service; /* if no _work object, after all thing done, the _service.run will continue then thread will end. */ boost::asio::io_service::work _work; boost::asio::deadline_timer _deadlineTimer; boost::thread _thread; }; }
#include "stdafx.h" #include "DelayEvent.h" #include <boost/bind.hpp> namespace kagula { CDelayEvent::CDelayEvent() :_work(_service), _deadlineTimer(_service) { boost::thread t(boost::bind(&boost::asio::io_service::run, &_service)); _thread = boost::move(t); } CDelayEvent::~CDelayEvent() { _service.stop(); _thread.join(); } void CDelayEvent::SendMessage(Callback callback, const HWND hwnd, const UINT msg, const WPARAM wParam, const LPARAM lParam, int millisecond) { _deadlineTimer.expires_from_now(boost::posix_time::milliseconds(millisecond)); _deadlineTimer.async_wait(boost::bind(callback, hwnd, msg, wParam, lParam)); } }