如何使WinForms TabPage标题宽度适应其标题?

6
如何使WinForms TabPage的标题宽度适合其标题? 这里是问题。enter image description here
3个回答

10

原生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);
}

3
感谢,Hans。 我使用了你的代码,而没有创建一个类。
//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);

0

你需要测量字体。

可以尝试这样做:

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

1
好的,我测量完了,接下来呢? - clumpter
TabPage没有宽度属性。 - clumpter
抱歉,我习惯了KryptonNavigators! 尝试一下... <tab>.Size.Width = GetTabWidth(<title>) - Richard.Gale
<tab>的Size是用于标签区域,而非标签头。 - clumpter
你真的相信所有选项卡标题都与“+”选项卡具有相同的小宽度是一个好主意吗? - clumpter
啊,没错,可能不是这样。我更喜欢KryptonNavigator,因为它有更多选项来调整标签的大小和样式。 - Richard.Gale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接