View类里面这三个得到的有区别?(SDI) CMainFrame* ss=(CMainFrame*)AfxGetMainWnd();
CMainFrame* ss=(CMainFrame*)GetParent();
CMainFrame* ss=(CMainFrame*)AfxGetApp()->m_pMainWnd;

解决方案 »

  1.   

    第一个和第三个在大多数情况下都是相等的吧
    第二个View是Mainframe子窗口时成立
      

  2.   

    测试了一下,用appWizard生成了一个单文档程序,1和3是一样的,但是2不同,不同呢?都应该指向CMainFrame啊?
    请指教!
      

  3.   

    CMainFrame* ss=(CMainFrame*)AfxGetMainWnd(); 
    CMainFrame* ss=(CMainFrame*)AfxGetApp()->m_pMainWnd; 
    这两条语句运行结果是相同的。至于CMainFrame* ss=(CMainFrame*)GetParent(); 嘛,只有作为CMainFrame的子窗口做调用,才能得到正确的结果。在对象Create(WM_CREATE消息映射)的时候,有一个参数(CWnd* pParent)就是用来指定当前对象的父窗口的。
      

  4.   

    CMainFrame* ss=(CMainFrame*)AfxGetMainWnd(); 
    CMainFrame* ss=(CMainFrame*)AfxGetApp()->m_pMainWnd;相同
    CMainFrame* ss=(CMainFrame*)GetParent(); 只有在特定的环境才正确,如果当前父窗口不是CMainFrame类型,很危险,通常还是建议用上面两种方法
      

  5.   

    楼上两位分析得很清楚!
    不过对于单文档来说,view窗口是Frame的子窗口,为什么得到的还是不一样呢?view窗口是不是Frame的子窗口呢?
      

  6.   

    SDI里一样啊。。怎么不一样?
      

  7.   


    不一样,我是这么测试的:
    class CTestView : public CView
    {
    public:
    CButton dd;

    }int CTestView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
    { CMainFrame* ss=(CMainFrame*)GetParent();
    // CMainFrame* ss=(CMainFrame *)AfxGetApp()->m_pMainWnd;
    dd.Create("sd",WS_VISIBLE,CRect(0,0,100,100),ss,104);
    dd.ShowWindow(SW_SHOW);}
    没问题int CTestView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
    {// CMainFrame* ss=(CMainFrame*)GetParent();
    CMainFrame* ss=(CMainFrame *)AfxGetApp()->m_pMainWnd;
    dd.Create("sd",WS_VISIBLE,CRect(0,0,100,100),ss,104);
    dd.ShowWindow(SW_SHOW);}
    有问题
      

  8.   

    看看类继承,view可不是它地子类!
      

  9.   

    把第二条语句的 GetParent() 换成 GetTopLevelFrame() 就一样了!
      

  10.   

    第一个在主线程用没有问题,在非主线程可能有异常
    第二个仅仅返回Parent,不能保证是CMainFrame
    第三个在任何线程使用都将返回主线程的CMainFrame,最好。
      

  11.   

    恩。
    这里GetParent()和GetTopLevelFrame( ) 一样,总的来说还是用GetTopLevelFrame( ),那两个AFX函数不能用。
      

  12.   

    看看MFC的框架类就明白了,我之前学习MFC的时候专门倒SRC的里面去看它的CPP实现部分,跟踪很详细,了解很透彻。
      

  13.   

    CMainFrame的CView都是CWnd的实例,程序初始化时,创建两个实例,CView中的GetParent,指向其自身实例的地址,即使强制转换,也不可能得到CMainFrame的指针。
      

  14.   


    怎么可能是自身呢?!
    自身this不就完了。
    CWnd::GetParent  
    CWnd* GetParent( ) const;Return ValueIdentifies the parent window if the member function is successful. Otherwise, the value is NULL, which indicates an error or no parent window. The returned pointer may be temporary and should not be stored for later use.