Add item to MFC list box from thread?

Pages: 12
@coder777
I wanted to update my list box from a thread, Thomas above suggested that I use SendMessage() for that purpose.
I am not entirely sure what you mean by you don't know what SendMessage() is doing?
If you be so kind as to elaborate a little, is there any other way around it.
My question is fairly simple "Update a list box from a thread".
Thanks a lot

@kbw: I cannot access control variable from a thread, that is the whole issue here.
I cannot access control variable from a thread, that is the whole issue here.
That's not entirely correct.

The worker thread is passed a pointer to the instance of the dialog box to be updated. You can add a method to that dialog box, then call it form the worker thread. For example:
1
2
3
4
void CCMFCApplication1Dlg::AddStringToListbox(const CString& str)
{
	SendMessage(m_list.m_hwnd, LB_ADDSTRING, 0, static_cast<const char*>(str));
}


The thread would then look like this:
1
2
3
4
5
6
7
8
9
10
UINT MyThreadProc(void *pParam)
{
	if (CCMFCApplication1Dlg* pMainDlg = (CMFCApplication1Dlg*)pParam) {
		// do some work
		// ...
		pMainDlg->AddStringToListbox("hello world");
	}

	return 0;
}


I initially suggested PostThreadMessage because you'll eventually run into problems by using SendMessage directly. The GDI doesn't (or didn't used to handle threads) and the paint messages etc run in the wrong thread.
Last edited on
Wow thanks, I read msdn article https://msdn.microsoft.com/en-us/library/69644x60.aspx on worker threads and then read your very accurate description.
I have better understanding now, will implement the example you gave and return with feedback.
Thanks again.
Update:
Apparently SendMessage() first parameter should be a UINT message, where as the example you gave has HWND has first parameter.
where as the example you gave has HWND has first parameter.
kbw is right. The problem with the function you were calling is that it most likeley denotes the wrong window. The dialog not the listbox.

Calling the global function:
::SendMessage(m_list.m_hwnd, LB_ADDSTRING, 0, static_cast<const char*>(str));
Yes the problem was solved by using your solution however I get this
error C2664: 'LRESULT SendMessageA(HWND,UINT,WPARAM,LPARAM)' : cannot convert argument 4 from 'const char *' to 'LPARAM'

Whats the best way to solve this?
This worked
::SendMessage(m_list.m_hWnd, LB_ADDSTRING, 0, (LPARAM)(LPCTSTR)str);
I was able to add text item into list box.
Will try with thread now and update here, thanks.
Topic archived. No new replies allowed.
Pages: 12