原文:
http://www.codeguru.com/Cpp/controls/controls/tabcontrols/article.php/c5239
作者:Ben Hill
环境:VC6 SP3, NT4, Windows 2000 Pro, Windows 2000 Server
首先,将CMyTabCtrl.cpp和CMyTabCtrl.h加入到你的项目中。然后,在Visual Studio中添加一个CTabCtrl控件到你的对话框中。同时为这个控件添加一个变量,这个变量的类型应该是CMyTabCtrl而不是简单的CTabCtrl。CMyTabCtrl是继承自CTabCtrl的。你可以先添加一个CTabCtrl类型的变量,然后手动的修改文件把它修改为CMyTabCtrl。(注:作者说的是VS 6.0中的情况,在VS 2005中,可以将“添加变量”对话框中的“变量类型”修改为:CMyTabCtrl,VS会自动地为你加上头文件引用)
现在为你需要的每一页创建对话框。它们都必须是无边框的子对话框。在这些对话框中的所有控件都拥有它们自己的类。
为每个对话框创建类。在例子中,它们是:CTabOne, CTabTwo and CTabThree。在CMyTabCtrl的构造函数中,你应该为每一页的类创建实例。在Init方法中,你还需要把除第一个页以外的其他对话框设为隐藏。
在本例中,消息OnLButtonDown的处理方法用于控制对话框的隐藏与显示。显示的页面的序号放在m_tabCurrent变量中。
在主程序对话框的OnInitDialog消息处理函数中加入页面。在本例中是:Tab One, Tab Two 和Tab Three。
m_tabMyTabCtrl.InsertItem(0, _T("Tab One"));
m_tabMyTabCtrl.InsertItem(1, _T("Tab Two"));
m_tabMyTabCtrl.InsertItem(2, _T("Tab Three"));
m_tabMyTabCtrl.Init();
以下是部分代码:
CMyTabCtrl::CMyTabCtrl()
{
m_tabPages[0]=new CTabOne;
m_tabPages[1]=new CTabTwo;
m_tabPages[2]=new CTabThree;
m_nNumberOfPages=3;
}
CMyTabCtrl::~CMyTabCtrl()
{
for(int nCount=0; nCount < m_nNumberOfPages; nCount++){
delete m_tabPages[nCount];
}
}
void CMyTabCtrl::Init()
{
m_tabCurrent=0;
m_tabPages[0]->Create(IDD_TAB_ONE, this);
m_tabPages[1]->Create(IDD_TAB_TWO, this);
m_tabPages[2]->Create(IDD_TAB_THREE, this);
m_tabPages[0]->ShowWindow(SW_SHOW);
m_tabPages[1]->ShowWindow(SW_HIDE);
m_tabPages[2]->ShowWindow(SW_HIDE);
SetRectangle();
}
void CMyTabCtrl::SetRectangle()
{
CRect tabRect, itemRect;
int nX, nY, nXc, nYc;
GetClientRect(&tabRect);
GetItemRect(0, &itemRect);
nX=itemRect.left;
nY=itemRect.bottom+1;
nXc=tabRect.right-itemRect.left-1;
nYc=tabRect.bottom-nY-1;
m_tabPages[0]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_SHOWWINDOW);
for(int nCount=1; nCount < m_nNumberOfPages; nCount++){
m_tabPages[nCount]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_HIDEWINDOW);
}
}
//
// CMyTabCtrl message handlers
void CMyTabCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
CTabCtrl::OnLButtonDown(nFlags, point);
if(m_tabCurrent != GetCurFocus()){
m_tabPages[m_tabCurrent]->ShowWindow(SW_HIDE);
m_tabCurrent=GetCurFocus();
m_tabPages[m_tabCurrent]->ShowWindow(SW_SHOW);
m_tabPages[m_tabCurrent]->SetFocus();
}
}