如何使WinForms TabPage标题宽度适合它的标题?

如何使WinForms TabPage标题宽度适合它的标题? 这是问题所在。

在此处输入图像描述

本机Windows选项卡控件允许覆盖默认的最小选项卡宽度。 遗憾的是,TabControl包装类中没有公开该function。 但这是可以修复的。 在项目中添加一个新类并粘贴下面显示的代码。 编译。 将新控件从工具箱顶部拖放到表单上。

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 =  Dim g As Graphics = tabPage.CreateGraphics() width = CType(g.MeasureString(valueToMeasure, tabPage.Font).Width, Integer) 

可能为填充添加一个额外的机器人(宽度=宽度+10)

编辑:

 .width = GetTabWidth() 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