Oct 232013

Why do you need to Select an MDI tab programmatically?

A customer recently asked this question on how to select an MDI tab programmatically, thought I’ll share the solution out here. 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 resultant application will look like…

MFC MDI TabsMFC MDI Tab Groups

MFC MDI Tab Groups

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

Code to Select an MDI tab programmatically

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));