MFC - Cannot send message to user class retrieved from CWnd

I have a custom class derived from CWnd that I would like to send a message from a workflow. For this, I use the PostMessage function. The first argument to PostMessage is an HWND type descriptor for my class, and the next is the message I would like to process. For the first parameter, I generate a descriptor in my class using the GetSafeHwnd () function, and for the second parameter I use WM_USER + 3. In addition, I declare a message map inside the class header file and add an entry for the message handler inside the BEGIN_MESSAGE_MAP and END_MESSAGE_MAP blocks. However, my handler is not called. I also checked the return value of the PostMessage function, it is 1, which means success.

Here is my code:

Inside MyClass.h

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

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

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 workflow

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

My question is what are the possible reasons why the OnMessageReceived handler will not be called.

PS

I take care that the caller calls the InitHandle () function.

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

+1
source share
1 answer

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

+1
source

All Articles