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

时间:2011-07-19 09:44:11

标签: c# winforms width tabcontrol tabpage

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

enter image description here

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:3)

谢谢,汉斯。 我在没有创建类

的情况下使用了您的代码
//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);

答案 2 :(得分: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