以下是一个简单的示例,演示如何在一个线程中使用 PostThreadMessage 向自己的消息队列中发送消息:
// 假设你的应用程序类为 CMyApp,线程类为 CMyThread
#include "CMyApp.h"
#include "CMyThread.h"
BOOL CMyApp::InitInstance()
{
// 创建并运行新线程
CMyThread* pThread = (CMyThread*)AfxBeginThread(RUNTIME_CLASS(CMyThread));
// 其他初始化工作...
return TRUE;
}
BOOL CMyThread::InitInstance()
{
// 在线程初始化时执行操作
// 示例:向自己的消息队列中发送消息
PostThreadMessage(WM_MY_CUSTOM_MESSAGE, 0, 0);
return CWinThread::InitInstance();
}
BEGIN_MESSAGE_MAP(CMyThread, CWinThread)
// 添加自定义消息处理函数
ON_THREAD_MESSAGE(WM_MY_CUSTOM_MESSAGE, OnMyCustomMessage)
END_MESSAGE_MAP()
BOOL CMyThread::OnMyCustomMessage(WPARAM wParam, LPARAM lParam)
{
// 处理自定义消息
// 示例:输出一条消息
TRACE(_T("Custom Message Received!\n"));
return TRUE;
}
在上述代码中,PostThreadMessage 用于在 CMyThread 线程的初始化过程中向自己的消息队列中发送一个自定义消息 WM_MY_CUSTOM_MESSAGE。CMyThread 类中通过 ON_THREAD_MESSAGE 宏添加了一个处理该消息的成员函数 OnMyCustomMessage。
请注意,PostThreadMessage 将消息投递到线程的消息队列,而不是直接调用消息处理函数。确保在你的消息处理函数中处理消息,并返回一个适当的值。
转载请注明出处:http://www.zyzy.cn/article/detail/23229/MFC/CWinThread