[MFC Feature Pack] Select an MDI tab programmatically in a Document View application

A customer recently asked this question, thought I’ll share the solution out here. Its not that obvious FYI. When creating an MFC MDI application we have an option to enable tabbed view of MDI documents. Once this is done here’s how the application will look like…



Note that except for the first sample image you have multiple tab groups in the rest of the screenshots , this is an inbuilt facility provided by the tabbing framework of MFC. This is important when selecting a tab programmatically: You’ll also have to decide which tab from which group you would like to select.

In MFC framework tab groups are represented by CMDIClientAreaWnd::GetMDITabGroups() which returns a member variable of type CObList. This is how the code looks like…

const CObList& GetMDITabGroups() const { return m_lstTabbedGroups; }

This is a list of tab controls. Each tab control in this group denotes a tab group. So when activating a tab we’ll have to decide which tab in a tab group should be activated.

Following sample code activates the first tab in all the tab groups. Please note tab index starts at zero.

void CMainFrame::OnViewActivatetab()
    const CObList& TabGrps = m_wndClientArea.GetMDITabGroups();
    for (POSITION pos = TabGrps.GetHeadPosition(); pos != 0;)
        CMFCTabCtrl* pNextWnd = DYNAMIC_DOWNCAST(CMFCTabCtrl, TabGrps.GetNext(pos));

Appreciate your comments...