现在的位置: 首页 > 综合 > 正文

向线程发送消息

2018年02月15日 ⁄ 综合 ⁄ 共 2176字 ⁄ 字号 评论关闭
class GLThread
{
public:
	GLThread();
	~GLThread();
	void Run();
	HANDLE GetHandle();
	DWORD GetThreadID();
protected:
	static unsigned int __stdcall ThreadFunc(LPVOID thisObj);
protected:
	HANDLE mThreadHandle;
	HANDLE threadSynchroEventHandle;
	DWORD mThreadId;
};

unsigned int __stdcall GLThread::ThreadFunc(LPVOID thisObj)
{
	GLThread * glThrd = (GLThread *)thisObj;
	
	MSG msg;
	PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
	SetEvent(glThrd->threadSynchroEventHandle);
	
	while (true)
	{
		GetMessage (&msg, NULL, 0, 0);
		int test = 0;
		test++;
	}
	return 0;
}

GLThread::GLThread()
	:mThreadHandle(0),
	mThreadId(0)
{
}

GLThread::~GLThread()
{
}

void GLThread::Run()
{
	//设置同步操作目的:当退出Run函数时 可以向线程发消息
	//如果不同步 发消息则可以失败
	threadSynchroEventHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
	//一定要换成beginthread
	unsigned threadID;
	unsigned int handle = _beginthreadex(0, 0, ThreadFunc, this, 0, &threadID);
	mThreadHandle =reinterpret_cast <HANDLE>(handle);
	mThreadId = threadID;
	WaitForSingleObject(threadSynchroEventHandle, INFINITE);
	CloseHandle(threadSynchroEventHandle);
}

HANDLE GLThread::GetHandle()
{
	return mThreadHandle;
}
DWORD GLThread::GetThreadID()
{
	return mThreadId;
}

发送消息到某线程的消息队列中。发送后,立即返回,不用等待此线程处理这个消息。

BOOL WINAPI PostThreadMessage(

  _In_  DWORD idThread,

  _In_  UINT Msg,

  _In_  WPARAM wParam,

  _In_  LPARAM lParam

);

参数

idThread [in]

Type: DWORD

发送消息到某线程的线程ID

如果此线程没有消息队列,此函数调用失败。当此线程第一次调用用户定义的函数或GDI函数时,系统创建线程的消息队列。详细信息参见"注意"部分。

Msg [in]

Type: UINT

消息类型

wParam [in]

Type: WPARAM

消息参数

lParam [in]

Type: LPARAM

消息参数

返回参数

Type: BOOL

如果函数调用成功,则返回非零值。

注意

要向线程发送消息必须要创建一个消息队列,否则调用PostThreadMessage函数会失败。使用下面的方法解决这个问题。

创建一个事件对象,然后创建一个线程。

在调用PostThreadMessage函数之前,使用WaitForSingleObject函数,等待事件对象被激发,

在接收消息的线程中,使用PeekMessage,强制系统创建一个消息队列。

PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE)

设置事件,指明此线程已经准备好了接收消息

接收消息的线程调用GetMessagePeekMessage接收消息。得到的MSG结构体中的hwnd成员为NULL

使用PostThreadMessage发送消息不需要绑定一个窗口。通常,没有与绑定窗口的消息不能使用DispatchMessage函数分发消息。因此,如果此线程在一个模态循环里(如果使用MessageBoxDialogBox),此消息将丢失。当在模态循环时,使用线程钩子截获线程。

操作系统不会marshalling系统消息(系统消息范围0WM_USER-1)。为了发送消息(大于等于WM_USER)给其它线程,你必须自定义marshalling

每一个消息队列至多能容纳10,000个消息。此限制已足够大了。如果你的程序想突破此限制,那应该重新设计来避免使用过多的系统资源。

为了修改此限制,可修改如下注册表中的键值

HKEY_LOCAL_MACHINE

   SOFTWARE

      Microsoft

         Windows NT

            CurrentVersion

               Windows

                  USERPostMessageLimit

抱歉!评论已关闭.