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

Many times we don’t want the MDI template dialog to be shown during startup of an MDI application.

Well the million dollar question is how can we prevent it from popping up. Well this is how we do it… 🙂

Goto your applicationname.cpp file and edit the InitInstance method at the specified place as shown here…

// Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo;

//this is the line that you should add
cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing;

// Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
    return FALSE;

There is a member variable in the class CCommandLineInfo which is called m_nShellCommand.

This is the variable that tells the command line parser to start a new file at startup.
This variable is by default set to FileNew. We have to assign a new value to this variable i.e. FileNothing.
Well this means empty file so MDI will be blank initially and the template dialog doesn’t pop up.

We have to click on New file to see the template dialog again and then choose any
template from a set of multiple templates that we have created.