今天写示例程序的时候,遇到了需要多行标题TabControl的情况。
整体流程很简单,就是将标题拆分,然后根据行数和最大行宽设置每一Page标题的高度及宽度即可。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; namespace UITabControlTest { public partial class SubForm : Form { private Dictionary<TabPage, TabPageInfo> allTabMap = new Dictionary<TabPage, TabPageInfo>(); public SubForm() { InitializeComponent(); tabMain.DrawMode = TabDrawMode.OwnerDrawFixed; } private void SubForm_Load(object sender, EventArgs e) { tabPage1.Text = "line1\nline2\nline3\nline4\nlin5"; tabPage2.Text = "line1\nline2\nline3\nline4"; tabPage3.Text = "line1\nline2\nline3"; tabPage4.Text = "line1\nline2"; int lineNum = 0; foreach (TabPage tab in this.tabMain.TabPages) { TabPageInfo pInfo = new TabPageInfo(tab.Text,"\n"); allTabMap.Add(tab, pInfo); lineNum = lineNum>pInfo.LineNum?lineNum:pInfo.LineNum; } foreach (TabPage tab in this.tabMain.TabPages) { TabPageInfo pInfo = allTabMap[tab]; tab.Text = pInfo.MaxLine; } //some thing is wrong, the font height is 14, the padding height is around 9, why? tabMain.Padding = new Point(0, Convert.ToInt32(tabMain.Font.Height * (lineNum - 1) * 0.65)); } private void tabMain_DrawItem(object sender, DrawItemEventArgs e) { TabControl tabControl = (TabControl)sender; TabPage currentTab = tabControl.TabPages[e.Index]; TabPageInfo info = allTabMap[currentTab]; string tabText = info.AllLine; StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; RectangleF tabRect = (RectangleF)e.Bounds; RectangleF textRect = tabRect; if (e.Index == tabControl.SelectedIndex) { tabRect.Inflate(1, 1); } Graphics g = e.Graphics; g.Clip = new Region(tabRect); g.Clear(Control.DefaultBackColor); g.ResetClip(); g.DrawString(tabText, e.Font, SystemBrushes.ControlText, textRect, sf); } } class TabPageInfo { public int LineNum { get { return nLineNum; } } public String MaxLine { get { //prevent auto wrap return szMaxLine+" "; } } public String getLine(int index) { if (index < nLineNum) { return szLines[index]; } else { return ""; } } public String AllLine { get { return szAllLine; } } private int nLineNum = 0; private String[] szLines; private String szAllLine; private String szMaxLine; public TabPageInfo(String pageTitle, String splitString) { szAllLine = pageTitle.Replace(splitString, "\n"); String [] separators = new String[]{splitString}; szLines = pageTitle.Split(separators,StringSplitOptions.RemoveEmptyEntries); nLineNum = szLines.Length; int nMaxLineWidth = 0; foreach(String line in szLines) { if (nMaxLineWidth < line.Length) { nMaxLineWidth = line.Length; szMaxLine = line; } } } } }