PostMessage from WorkerThread to the main window in MFC

I have an MFC application in which there is a workflow, what I want to do is send a message from the workflow to the main GUI thread to update some status messages in the GUI. What I have done so far is Registered a new window message

 //custom messages static UINT FTP_APP_STATUS_UPDATE = ::RegisterWindowMessageA("FTP_APP_STATUS_UPDATE"); 

Added this message to the dialog class message map

 ON_MESSAGE(FTP_APP_STATUS_UPDATE, &CMFC_TestApplicationDlg::OnStatusUpdate) 

The prototype of OnStatusUpdate is

 afx_msg LRESULT OnStatusUpdate(WPARAM, LPARAM); 

and definition

 LRESULT CMFC_TestApplicationDlg::OnStatusUpdate(WPARAM wParam, LPARAM lParam) { //This function is not called at all. return 0; } 

and workflow call code

 void CMFC_TestApplicationDlg::OnBnClickedMfcbutton1() { ThreadParams params; params.m_hWnd = m_hWnd; params.FTPHost = "test_host"; params.FTPUsername = "test"; params.FTPPassword = "test"; AfxBeginThread(FTPConnectThread,&params); } 

and workflow code

 //child thread function UINT FTPConnectThread( LPVOID pParam ) { if(pParam == NULL) { return 0; } ThreadParams *params = (ThreadParams*)pParam; OutputDebugString(params->FTPHost); Sleep(4000); //simulating a network call CString * message = new CString("Conencted"); PostMessage(params->m_hWnd,FTP_APP_STATUS_UPDATE,0,(LPARAM)message); //PostMessage do nothing? what I am doing wrong? return 1; } 

the problem is that a PostMessage function called OnStatusUpdate must be called, but it is not called, an exception or statement is not thrown, what am I doing wrong? I tried ON_REGISTERED_MESSAGE and ON_MESSAGE but did not succeed, no help?

+6
source share
1 answer

CMFC_TestApplicationDlg::OnBnClickedMfcbutton1() may return before the start of the stream. This leads to the fact that your ThreadParams goes out of scope, so when you access it from a thread, you get access to free memory. You need to select it in another way, for example:

 void CMFC_TestApplicationDlg::OnBnClickedMfcbutton1() { ThreadParams* params = new ThreadParams(); params->m_hWnd = m_hWnd; params->FTPHost = "test_host"; params->FTPUsername = "test"; params->FTPPassword = "test"; AfxBeginThread(FTPConnectThread,params); } //child thread function UINT FTPConnectThread( LPVOID pParam ) { if(pParam == NULL) { return 0; } ThreadParams *params = (ThreadParams*)pParam; OutputDebugString(params->FTPHost); Sleep(4000); //simulating a network call CString * message = new CString("Conencted"); PostMessage(params->m_hWnd,FTP_APP_STATUS_UPDATE,0,(LPARAM)message); delete params; return 1; } 
+5
source

Source: https://habr.com/ru/post/916447/


All Articles