1、将标题添加进tabpage中
public void Add_TabPage(string str, Form myForm) //将标题添加进tabpage中
{
if (!this.tabControlCheckHave(this.MainTabControl, str))
{
this.MainTabControl.TabPages.Add(str);
this.MainTabControl.SelectTab((int)(this.MainTabControl.TabPages.Count - 1));
myForm.FormBorderStyle = FormBorderStyle.None;
myForm.TopLevel = false;
myForm.Show();
myForm.Parent = this.MainTabControl.SelectedTab;
}
}
2、看tabpage中是否已有窗体
public bool tabControlCheckHave(TabControl tab, string tabName) //看tabpage中是否已有窗体
{
for (int i = 0; i < tab.TabCount; i++)
{
if (tab.TabPages[i].Text == tabName)
{
tab.SelectedIndex = i;
return true;
}
}
return false;
}
3、添加tabpage标题,并添加嵌套窗体
private void btnService_Click(object sender, EventArgs e)
{
this.Add_TabPage("维护 ", new frmServiceMain());
}
4、继而,选中tabControl控件属性修改 DrawMode = OwnerDrawFixed,再根据如下代码添加即可:
5、
private void MainTabControl_DrawItem(object sender, DrawItemEventArgs e)
{
/*如果将 DrawMode 属性设置为 OwnerDrawFixed,
则每当 TabControl 需要绘制它的一个选项卡时,它就会引发 DrawItem 事件*/
try
{
this.MainTabControl.TabPages[e.Index].BackColor = Color.LightBlue;
Rectangle tabRect = this.MainTabControl.GetTabRect(e.Index);
e.Graphics.DrawString(this.MainTabControl.TabPages[e.Index].Text, this.Font, SystemBrushes.ControlText, (float)(tabRect.X + 2), (float)(tabRect.Y + 2));
using (Pen pen = new Pen(Color.White))
{
tabRect.Offset(tabRect.Width - 15, 2);
tabRect.Width = 15;
tabRect.Height = 15;
e.Graphics.DrawRectangle(pen, tabRect);
}
Color color = (e.State == DrawItemState.Selected) ? Color.LightBlue : Color.White;
using (Brush brush = new SolidBrush(color))
{
e.Graphics.FillRectangle(brush, tabRect);
}
using (Pen pen2 = new Pen(Color.Red))
{
Point point = new Point(tabRect.X + 3, tabRect.Y + 3);
Point point2 = new Point((tabRect.X + tabRect.Width) - 3, (tabRect.Y + tabRect.Height) - 3);
e.Graphics.DrawLine(pen2, point, point2);
Point point3 = new Point(tabRect.X + 3, (tabRect.Y + tabRect.Height) - 3);
Point point4 = new Point((tabRect.X + tabRect.Width) - 3, tabRect.Y + 3);
e.Graphics.DrawLine(pen2, point3, point4);
}
e.Graphics.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
6.
private void MainTabControl_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{ www.2cto.com
int x = e.X;
int y = e.Y;
Rectangle tabRect = this.MainTabControl.GetTabRect(this.MainTabControl.SelectedIndex);
tabRect.Offset(tabRect.Width - 0x12, 2);
tabRect.Width = 15;
tabRect.Height = 15;
if ((((x > tabRect.X) && (x < tabRect.Right)) && (y > tabRect.Y)) && (y < tabRect.Bottom))
{
this.MainTabControl.TabPages.Remove(this.MainTabControl.SelectedTab);
}
}
}