[英]mfc c++ send a custom user message with postmessage from a working thread to main ui thread
使用Visual Studio 2015(社區版)和MFC C ++項目。 我有一個工作線程,我希望使用PostMessage()函數將數據從該線程發送到主UI線程(我的CDialog所在的位置),但仍在同一類中,我想接收此消息。
在MyComm.h文件中,我具有以下內容:
#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);
...
};
在我的MyComm.cpp文件中,我具有以下內容:
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;
...
}
注意,我將其中的一些縮寫保留在主題上。
在調試此代碼(比這更多的代碼)時,我驗證線程已啟動,並執行此PostMessage()函數,該函數返回true。 我從來沒有去過打算作為接收者的OnResponse()函數。 我不確定為什么..(??)..
一些想法。 的確,類MyComm在同一個類中,但不是對話框線程,而是由它派生的,並且是從CDialog派生的。 這可能還不夠?? 我承認,通過MFC編程范例,我對線程還是有些陌生。 任何幫助表示贊賞。
瘋狗
string s
將不存在。 您顯示的線程函數太小,將很快退出。 OnInitDialog
而不是在構造函數中啟動新線程。 消息循環不是在構造函數中創建的,而是在OnInitDialog
。 WM_USBRDRESPONSE
和WM_USBRDRESPONSE
今天,我確實找到了這個問題的答案。
這是因為啟動線程的類還不是與窗口綁定的類,而是由帶有窗口的類生成的。 因此,對pMyHndl
的細微差別是必要的。 如果在POSTMESSAGE()
我改為使用pMyHndl->m_pParent
代替m_pParent指向Parent類的位置(一個帶窗口的位置)。 現在,此代碼正在接收消息,因為接收消息的代碼已移動到那里。 謝謝各位的幫助。
瘋狗
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.