Click to See Complete Forum and Search --> : Problem with Threads
nirankul2003
November 24th, 2004, 05:42 AM
hi i am writing an MFC SDI application that spawns a worker thread.
I want the thread to print its output in view.(The view is readonly CEditView that displays output similar to a logfile to the user).
how do i make the thread to access my view?
Ajay Vijay
November 24th, 2004, 06:07 AM
Are you aware of synchronization issues of objects between threads - specfically MFC objects. Note that MFC objects cannot be passed directly between threads, and you need to pass the HWND of object. And in the second thread you can get pointer to actual object using CWnd::FromHandle.
Other than that, you must sync. writing to the view - that is only one thread should be allowed to draw on the view/window at a time.
darwen
November 24th, 2004, 06:24 AM
You shouldn't really be using CWnd::GetHandle either.
Effectively what you need to do is :
(1) Pass the HWND of your view to the thread.
(2) In the view have a specific message & handler to tell it that there's messages to display
(3) When the thread wants to display a message it should
- SendMessage() to the HWND with the message to be displayed.
For example :
class CMyView : public CView
{
public:
static const int m_nMessage;
// ....
protected:
LRESULT OnThreadMessage(WPARAM wParam, LPARAM lParam);
};
// in .cpp
const CMyView::m_nMessage = ::RegisterWindowMessage("MyViewMessage");
BEGIN_MESSAGE_MAP(CMyView, CView)
ON_REGISTERED_MESSAGE(m_nMessage, OnThreadMessage)
END_MESSAGE_MAP()
LRESULT CMyView::OnThreadMessage(WPARAM wParam, LPARAM lParam)
{
// get the thread's messages and display.
LPCSTR szMessage = (LPCSTR)wParam;
// display the message however you want to.
return S_OK;
}
// in thread func
CString sMessage = "this is a message";
::SendMessage(m_hWndView, CMyView::m_nMessage, (LPCSTR)sMessage, 0);
Effectively what you're doing is called marshalling - and using windows messaging is a tried and tested method. Even COM uses this in some cases.
This is the safest way of doing this.
Darwen.
Andreas Masur
November 24th, 2004, 07:25 AM
The answer can be found in the following FAQ (http://www.codeguru.com/forum/showthread.php?t=312454)...
Andreas Masur
November 24th, 2004, 07:27 AM
[ Moved thread ]
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.