m_pMainWnd

 今天写程序时遇到个简单而又很有意思的问题,封装了一个网络接口类,发送数据以及网络的回调接口都在这个类里面,打算在回调函数里给AfxGetMainWnd()发送消息以更新主界面的数据,同时程序有一个登录框,需要在登录的回调函数里判断是否登录成功,以决定是否显示主界面,于是就想到这样做:

 view plaincopy to clipboardprint?
BOOL CXXXApp::InitInstance()  
{  
    //...  
      
    CDlgLogin dlgLogin;   
    m_pMainWnd = &dlgLogin;  
    if (IDCANCEL == dlgLogin.DoModal())  
    {  
        return FALSE;  
    }  
      
    CMainDlg dlg;  
    m_pMainWnd = &dlg;  
    int nResponse = dlg.DoModal();  
    if (nResponse == IDOK)  
    {  
        // TODO: Place code here to handle when the dialog is  
        //  dismissed with OK  
    }  
    else if (nResponse == IDCANCEL)  
    {  
        // TODO: Place code here to handle when the dialog is  
        //  dismissed with Cancel  
    }  
 
    return FALSE;  

BOOL CXXXApp::InitInstance()
{
 //...
 
 CDlgLogin dlgLogin; 
 m_pMainWnd = &dlgLogin;
 if (IDCANCEL == dlgLogin.DoModal())
 {
  return FALSE;
 }
 
 CMainDlg dlg;
 m_pMainWnd = &dlg;
 int nResponse = dlg.DoModal();
 if (nResponse == IDOK)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with OK
 }
 else if (nResponse == IDCANCEL)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with Cancel
 }

 return FALSE;
}

这样的话,登录的回调消息就可以发送到CDlgLogin对话框里,运行的时候却发现程序直接退出了。后来查了资料,才知道m_pMainWnd关联的对话框关闭时,如果该线程是主线程,则程序会终止。

“用该成员变量去存储你的线程主窗口对象。当和m_pMainWnd 相关的窗口被关闭后,MFC会自动终止你的线程。如果该线程是应用程序主线程,程序也将会被终止。如果该数据成员为NULL,应用程序CWinApp对象的主窗口将用来决定什么时候去终止线程。m_pMainWnd是一个CWnd*类型的public变量。
     很明显,你需要在重载InitInstance时为m_pMainWnd赋值。在工作线程中,m_pMainWnd自动继承其父线程的值。”

    后来在CDlgLogin类里,在窗口销毁之前,对m_pMainWnd赋空,问题解决。

view plaincopy to clipboardprint?
AfxGetApp()->m_pMainWnd = NULL;  
CDialog::OnOK(); 

原文地址:https://www.cnblogs.com/tianlangshu/p/2004076.html