Exit application using thread in MFC SDI
I have a SDI application. I created a method OnClose to handle ON_WM_CLOSE of CMainFrm. This onclose() function calls a method in cmyview.cpp. Here, I created a thread that calls global function and from this function it calls another function in cmyview.cpp. At certain condition my application should close at here, I used postmessgae(WM_CLOSE (or) WM_DESTROY). I am having an error as object reference not set on postmessage(WM_CLOSE) it is going to afxwin2.inl page where exception occurs.
Below is code snippet:(Here, either j or k will only be true depneds on user input)
MainFrm.cpp:
void CMainFrame::OnClose()
{
CMyView* pview = (CMyView*)((CFrameWnd*)AfxGetMainWnd())->GetActiveView();
pview->method1();
}
CMyView.cpp:
void CMyView::method2()
{
int i =1;
bool j, k
while(i==1)
{
if (j)
{
i=2;
PostMessage(WM_CLOSE);
}
else if (j)
{
i=2;
}
}
}
UINT thredproc1(LPVOID lpvoid)
{
CMyView* pMyView = (CMyView*)lpvoid;
pMyView->method2();
return 0;
}
void CMyView::method1()
{
CWinThread* pthread = AfxBeginThread(thredproc1,this,0);
}
Re: Exit application using thread in MFC SDI
1. Please use code tags. Your code is unreadable without them.
2. Does the code you posted actually replicate the problem?
3. You are using uninitialized variables. j is never assigned a value. Also, your else if will never be executed.
Code:
void CMyView::method2()
{
int i =1;
bool j, k
while(i==1)
{
if (j)
{
i=2;
PostMessage(WM_CLOSE);
}
else if (j)
{
i=2;
}
}
}
Re: Exit application using thread in MFC SDI
Hello!
You are only allowed to call MFC user-interface objects from a single thread.
The reason is that the message loop may pump messages while your thread is running, and objects may be destroyed and modified which would crash your program.
If you try to do something like your example in C#, it will stop immediately and give you an error. In C++ you will, as you have noticed, instead get an application failure.
Regards
Re: Exit application using thread in MFC SDI
Also let me add that although you are not allowed to invoke objects from a thread, you can still send a message to the window handle.
Code:
CWinThread* pthread = AfxBeginThread(thredproc1,this->m_hWnd,0);
UINT thredproc1(LPVOID lpvoid)
{
Sleep(1000);
::PostMessage((HWND)lpvoid, WM_CLOSE, 0, 0);
return 0;
}