How can i make WinForms TabPage header width fit it's title? Here is the problem.
Asked
Active
Viewed 8,578 times
3 Answers
10
The native Windows tab control allows overriding the default minimum tab width. Sadly that capability is not exposed in the TabControl wrapper class. That's fixable though. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.
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);
}

Hans Passant
- 922,412
- 146
- 1,693
- 2,536
3
Thanks, Hans. I used your code without creating a class
//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);

edid
- 349
- 3
- 8
0
You need to measure the fonts.
Try something like this:
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)
Probably add a bot extra on for padding (width = width +10)
Edited:
<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

Richard Gale
- 1,816
- 5
- 28
- 45
-
1Ok, i mesured it, what's next? – clumpter Jul 19 '11 at 10:13
-
TabPage doesn't have width property. – clumpter Jul 19 '11 at 10:27
-
Sorry, Im used to KryptonNavigators! Try...
.Size.Width = GetTabWidth( – Richard Gale Jul 19 '11 at 10:35) -
.Size is for tab area, not for tab header. – clumpter Jul 19 '11 at 10:39
-
Do you really believe that all tabs headers having the same small width as '+' tab is a good idea? – clumpter Jul 19 '11 at 11:08
-
ah, true, probably not. I prefer the KryptonNavigator as you have so many more options for the sizing and styling of the tabs – Richard Gale Jul 19 '11 at 11:15