MFC - 无法发布消息到从CWnd派生的自定义类 [英] MFC - Cannot Post Message to a custom class derived from CWnd

查看:327
本文介绍了MFC - 无法发布消息到从CWnd派生的自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类派生自CWnd,我想从工作线程发布消息。我使用PostMessage函数来实现这一点。 PostMessage的第一个参数是我的类的HWND类型句柄,下一个是我想处理的消息。对于第一个参数,我使用GetSafeHwnd()函数生成我的类的句柄,对于第二个参数,我使用WM_USER + 3。此外,我在类头文件中声明一个消息映射,并在BEGIN_MESSAGE_MAP和END_MESSAGE_MAP块中为消息处理程序添加一个条目。但是,我的处理程序没有得到调用。我也检查了PostMessage函数的返回值,它是1,这意味着成功。

I have a custom class derived from CWnd that I would like to post a message to from a worker thread. I am using the PostMessage function to achieve this. The first argument to PostMessage is the HWND type handle to my class, and the next is the message I would like handled. For the first parameter, I generate the handle to my class using GetSafeHwnd() function, and for the second parameter, I use WM_USER+3. Also, I declare a message map inside my class header file, and add an entry for the message handler inside the BEGIN_MESSAGE_MAP and END_MESSAGE_MAP block. However, my handler is not getting called. I have also checked the return value of PostMessage function, it is 1, that means success.

这是我的代码:

MyClass.h内部

Inside MyClass.h

class CMyClass : CWnd
{
....
.... 
public:
void InitHandle();

protected:
afx_msg LRESULT OnMessageReceived(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
} 

Inside MyClass.cpp

Inside MyClass.cpp

#define WM_MY_MESSAGE WM_USER+3

HWND handleToMyClassWindow;

BEGIN_MESSAGE_MAP(CMyClass, CWnd)
    ON_MESSAGE(WM_MY_MESSAGE, OnMessageReceived)
END_MESSAGE_MAP()

LRESULT CMyClass::OnMessageReceived(WPARAM wParam, LPARAM lParam)
{ .... }

void CMyClass::InitHandle()
{ 
    handleToMyClassWindow = GetSafeHwnd();
}

Inside Worker线程

Inside Worker thread

UINT WorkerThreadFunction(LPVOID pParam )
{ 
....
PostMessage(handleToMyClassWindow, WM_MY_MESSAGE, NULL, NULL);
....
}

我的问题是,原因为OnMessageReceived处理程序未被调用。

My question is, what are the possible reasons for the OnMessageReceived handler to not be called.

PS

我注意调用对象调用

我尝试了与我的程序的View类(从CView派生)相同的技术,它在那里工作,但在这里失败。

I tried the same technique with the View class (derived from CView) of my program, and it works there, but fails here.

推荐答案

如果尚未创建,您将无法发布到窗口。如果你没有使用你的类实际创建一个窗口,GetSafeHwnd()将返回NULL。

You cannot post to a window if it has not been created. GetSafeHwnd() will return NULL if you have not actually created a window using your class.

这篇关于MFC - 无法发布消息到从CWnd派生的自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆