您的位置:首页 > 其它

延迟一段时间调用SendMessage发送Windows消息

2014-10-16 17:14 351 查看
#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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐