MFC线程里调用AfxGetMainWnd的陷阱
如果直接在线程里调用AfxGetMainWnd可能会出错,原因:
_AFXWIN_INLINE CWnd* AFXAPI AfxGetMainWnd()
{ CWinThread* pThread = AfxGetThread();
return pThread != NULL ? pThread->GetMainWnd() : NULL; }
而AfxGetThread获取的是当前线程,而不是主线程!
CWinThread* AFXAPI AfxGetThread()
{
// check for current thread in module thread state
AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState();
CWinThread* pThread = pState->m_pCurrentWinThread;
return pThread;
}
解决办法可以参考http://blog.csdn.net/genius52/archive/2009/01/16/3797863.aspx
其实AfxGetApp()->m_pMainWnd就是“真正”的主线程窗口了!也就是说:
CWnd* pMainWnd = AfxGetMainWnd();
要改写成下面就OK了:
CWnd* pMainWnd = AfxGetApp()->m_pMainWnd;