Using CTabCtrl in MFC application

Steps to create dialog with tab control.
========================================

1. Add new dialog name it CTabDlg

2. Add a tab control and link with variable m_cTab.

3. Add message handlers for tab control.
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, &CTabDlg::OnTabChanged)
ON_NOTIFY(TCN_SELCHANGING, IDC_TAB1, &CTabDlg::OnTabChanging)

4. Add another variable std::vector m_vPages;

5. Add new dialogs CPageOneDlg, CPageTwoDlg, CPageThreeDlg
Make sure above three dialogs have style “Child” and Title bar “FALSE”.

6. Add below snippet in CTabDlg::OnInitDialog()
CTabDlg::OnInitDialog()
{
m_vPages.push_back(new CPageOneDlg(this));
m_vPages.push_back(new CPageTwoDlg((this));
m_vPages.push_back(new CPageThreeDlg((this));

m_vPages[0]->Create(CPageOneDlg::IDD, &m_cTab);
m_vPages[1]->Create(CPageTwoDlg::IDD, &m_cTab);
m_vPages[2]->Create(CPageThreeDlg::IDD, &m_cTab);

RECT r;
TCITEM tci;

GetClientRect(&r);

tci.mask = TCIF_TEXT;
tci.iImage = -1;

tci.pszText = L"Page One";
m_cTab.InsertItem(0, &tci);

tci.pszText = L"Page Two";
m_cTab.InsertItem(1, &tci);

tci.pszText = L"Page Three";
m_cTab.InsertItem(1, &tci);

OnTabChanged(NULL, NULL);
}

7. Below given are tab change event handler.

void CTabDlg::OnTabChanged(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: Add your control notification handler code here
RECT rc;
m_cTab.GetItemRect(0,&rc);
int nIndex = m_cTab.GetCurSel();

m_vPages[nIndex]->SetWindowPos( NULL, rc.left + 1, rc.bottom + 1, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW);
m_vPages[nIndex]->SetFocus();
}

void CTabDlg::OnTabChanging(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: Add your control notification handler code here
m_vPages[m_cTab.GetCurSel()]->ShowWindow(SW_HIDE);
*pResult = 0;
}

8. Now clean up work

CTabDlg::~CTabDlg()
{
m_vPages[0]->DestroyWindow();
m_vPages[1]->DestroyWindow();

delete m_vPages[0];
delete m_vPages[1];

m_vPages.clear();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: