Is the WIN95 version of GetActiveDocument broken?

No matter what I do, GetActiveDocument() seems to always return NULL. For example, I build a MDI app called Test using VC++5, accepting all the Wizard defaults. Then I add a menu item called Test, and add a handler to the CTestView class as shown below:

void CTestView::OnTest()
    CTestDoc* pDoc = GetDocument();

    CFrameWnd* pFrame = DYNAMIC_DOWNCAST(CFrameWnd,theApp.m_pMainWnd);

    if (pFrame)
        CDocument* pGenericDoc = pFrame->GetActiveDocument();

        CTestDoc* pTestDoc = DYNAMIC_DOWNCAST(CTestDoc,pGenericDoc);

theApp is the CTestApp instance produced by the wizard; I add "extern CTestApp theApp;" at the top of TestView.cpp.

When I run the app, I of course get the standard initial blank document, so THERE IS an active document, and sure enough, the call to CTestView::GetDocument returns non-null (I put this in just to make sure I wasn't nuts). The rest of the code in the handler is copied from Mike Blaszczak's "Professional MFC" book, page 185, which gives an example of how you get a pointer to the current document from some place other than your view class.

Anyway, the ASSERT(pGenericDoc) always blows. pFrame is non-NULL, but maybe isn't initialized by MFC to actually point to the main window?? Have I maybe found something that works under NT but not 95??
Who is Participating?
ambyConnect With a Mentor Commented:
In sted of simple use of:

because you are in a view, you must:

you already have FrameWnd here because of your pFrame, so the anwer is:


Have a nice day...

Get the acvive document through:
1. the document template
2. the application
jadcockAuthor Commented:
Re shaig answer: (2) is what I'm trying! theApp IS the application instance. Incidentally, rather than using theApp, AfxGetApp() will also give the same results. The question is, when, if ever, does GetActiveDocument() work?
jadcockAuthor Commented:
Yes!!! The extra GetActiveFrame() fixes it. I suspect the original code might work for an SDI app (no child frames)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.