如何使WinForms TabPage的标题宽度适合其标题?
这里是问题。
![enter image description here](https://istack.dev59.com/ML2DS.webp)
原生Windows标签控件允许覆盖默认的最小标签宽度。遗憾的是,这种能力在TabControl包装类中没有被暴露出来。不过这是可以解决的。在项目中添加一个新类,并粘贴下面展示的代码,编译后从工具箱顶部拖放新的控件到您的窗体上。
using System;
using System.Windows.Forms;
class MyTabControl : TabControl {
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
// Send TCM_SETMINTABWIDTH
SendMessage(this.Handle, 0x1300 + 49, IntPtr.Zero, (IntPtr)10);
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}
//InitializeComponent
this.tabPresentations.HandleCreated += new System.EventHandler(TabControl_HandleCreated);
void TabControl_HandleCreated(object sender, System.EventArgs e)
{
// Send TCM_SETMINTABWIDTH
SendMessage((sender as TabControl).Handle, 0x1300 + 49, IntPtr.Zero, (IntPtr)4);
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
你需要测量字体。
可以尝试这样做:
Dim tabPage As New TabPage
Dim width As Integer = 0
Dim valueToMeasure As String = <Your title Here>
Dim g As Graphics = tabPage.CreateGraphics()
width = CType(g.MeasureString(valueToMeasure, tabPage.Font).Width, Integer)
可能要额外添加一个机器人进行填充(宽度=宽度+10)
已编辑:
<tab>.width = GetTabWidth(<Title>)
Private Function GetTabWidth (Byval title as String) as Integer
Dim widthValue as Integer = 10 'Padding (Optional)
Dim tabPage as New tabPage
Dim g as Graphics = tabPage.CreateGraphics()
widthValue += Ctype(g.measureString(title, tabPage.Font).Width, Integer)
Return widthValue
End Function