Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MFC: CDocument* GetActiveDocument()

Status
Not open for further replies.

chpicker

Programmer
Apr 10, 2001
1,316
For some reason I can't get this function to work.

I'm following a tutorial in a book I bought from Sam's Publishing. I created an MDI application using the MFC AppWizard. In the Main Frame class I am supposed to put in a message handler for a toolbar action. The handler needs to call a function in my document class. To do this, I need to obtain a pointer to the document. The GetActiveDocument() function is supposed to do this. However, when I run my program it always returns NULL. Here's the code snippet:
[tt]
CDocument* pDoc=GetActiveDocument();
if (pDoc)
MessageBox("Obtained pointer");
else
MessageBox("Failed to obtain pointer");
[/tt]
I've tried opening several windows so there are plenty of documents to choose from. I switch between all the windows and try the toolbar action from each in turn. Every time, I get my failure message box on the screen.

Any suggestions?
 
I took a look at the MSDN Library and I found the following code. I tried it and it seems to work.

In your CDoc class create a function GetDoc()

CMyDoc * CMyDoc::GetDoc()
{
CMDIChildWnd * pChild =
((CMDIFrameWnd*)(AfxGetApp()->m_pMainWnd))->MDIGetActive();

if ( !pChild )
return NULL;

CDocument * pDoc = pChild->GetActiveDocument();

if ( !pDoc )
return NULL;

// Fail if doc is of wrong kind
if ( ! pDoc->IsKindOf( RUNTIME_CLASS(CMyDoc) ) )
return NULL;

return (CMyDoc *) pDoc;
}

Obviously insted of CMyDoc you have to write your CDoc class.

Therefore, whenever you need a pointer to the current doc you just have to write something like that

CMyDoc *pMyDoc = NULL;
pMyDoc = pMyDoc->GetDoc();

That's all, I hope this helps.
By
Triac
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top