Article ID: 108587
Article Last Modified on 11/21/2006
// Document header file
class CMyDoc : public CDocument
{
...
public:
static CMyDoc * GetDoc();
...
};
For a single document interface (SDI) application, add the following code
to your SDI document's implementation file for CMyDoc::GetDoc():
// SDI document implementation file
CMyDoc * CMyDoc::GetDoc()
{
CFrameWnd * pFrame = (CFrameWnd *)(AfxGetApp()->m_pMainWnd);
return (CMyDoc *) pFrame->GetActiveDocument();
}
For a multiple document interface (MDI) application, the CMyDoc::GetDoc()
code should be the following:
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;
}
To allow you to get a pointer to the currently active view from anywhere in
the program, add a static member function to your CView derived class as
follows:
// View header file
class CMyView
{
...
public:
static CMyView * GetView();
...
};
For an SDI application, add the following code to your SDI view's
implementation file for CMyView::GetView():
// View implementation file
CMyView * CMyView::GetView()
{
CFrameWnd * pFrame = (CFrameWnd *)(AfxGetApp()->m_pMainWnd);
CView * pView = pFrame->GetActiveView();
if ( !pView )
return NULL;
// Fail if view is of wrong kind
// (this could occur with splitter windows, or additional
// views on a single document
if ( ! pView->IsKindOf( RUNTIME_CLASS(CMyView) ) )
return NULL;
return (CMyView *) pView;
}
For an MDI application, the CMyView::GetView() code should be the
following:
// MDI view implementation file
CMyView * CMyView::GetView()
{
CMDIChildWnd * pChild =
((CMDIFrameWnd*)(AfxGetApp()->m_pMainWnd))->MDIGetActive();
if ( !pChild )
return NULL;
CView * pView = pChild->GetActiveView();
if ( !pView )
return NULL;
// Fail if view is of wrong kind
if ( ! pView->IsKindOf( RUNTIME_CLASS(CMyView) ) )
return NULL;
return (CMyView *) pView;
}
Now, from anywhere in your program, where the document or view header files
have been included, you can call:
CMyDoc::GetDoc();
- Or -
CMyView::GetView();to get a pointer to the currently active document or view, respectively. These functions return NULL if there is no active document or view.
Additional query words: kbSweptVC600
Keywords: kbhowto kbdocview KB108587