Using Visual Studio 2015 (Community Edition) & MFC C++ project. I have a worker thread where I wish to use PostMessage() function to send data from this thread to the main UI thread (where my CDialog resides) yet in the same class, that I want to receive this message.
In the MyComm.h file, I have the following:
#define WM_USERRESPONSE WM_APP + 2000
class MyComm: public CDialog
{
...
CWnd* m_pParent;
static BOOL m_bThreadKill;
static CWinThread* pThread;
static CEvent* pEvent;
static CEvent m_ThreadKillEvent;
...
static UINT MyThreadProc(LPVOID pParam);
...
afx_msg LRESULT OnResponse(WPARAM wParam, LPARAM lParam);
...
};
In my MyComm.cpp file, I have the following:
MyComm::MyComm(CWnd* pParent /*=NULL*/)
: CDialog(IDD_PPAGE_COMMAND, pParent)
{
m_pParent = pParent;
pEvent = new CEvent(FALSE, FALSE);
if ((pThread = AfxBeginThread(MyThreadProc, this)) == NULL)
AfxMessageBox("Could not Create Read Thread!");
pThread->m_bAutoDelete = FALSE;
m_ThreadKillEvent.ResetEvent();
m_ReadThreadDead.ResetEvent();
running = 1;
}
UINT MyComm::MyThreadProc(LPVOID pParam)
{
MyComm *pMyHndl = ((MyComm*)pParam);
string s = "I would like this string posted";
BOOL b = false;
b = ::PostMessage(pMyHndl->GetSafeHwnd(), WM_USBRDRESPONSE, 0,
(LPARAM)&s);
}
BEGIN_MESSAGE_MAP(MyComm, CDialog)
ON_MESSAGE(WM_USERRESPONSE, &MyComm::OnResponse)
END_MESSAGE_MAP()
afx_msg LRESULT MyComm::OnResponse(WPARAM wParam, LPARAM lParam)
{
MyStruct* p = (MyStruct*)lParam;
...
}
Note I abbreviated some of this to stay on topic.
In debugging this (there is much more code than this), I verify that the thread starts, I execute this PostMessage() function which returns true. I never get to the OnResponse() function that is intended to be the recipient. I am not sure why..(??)..
Some thoughts. It is true that the class MyComm is in the the same class yet is not the dialog thread, yet is spawned by it and is derived from CDialog. This may not be sufficient?? I admit, I am still somewhat new to threads via MFC programming paradigm. Any help is appreciated.
Maddog