I am trying to set DrawMode to OwnerDrawFixeddraw and then draw tab title the same way TabControl does with Normal DrawMode, but DrawString method with default parameters gives different results.
In the example below if text is set to Lorem ipsum it works, but if it's set to digits - it draws outside of tab area. Yet TabControl with Normal DrawMode draws everything correctly, how to do the same manually?
using System.Drawing;
using System.Windows.Forms;
namespace TabWidthIssue
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; // Works fine!
var text = "1234567890-1234567890-1234567890-1234567890-1234567890-123456789X"; // Does not fit!
// TabControl with OwnerDrawFixed
var ownerDrawFixedTabControl = new TabControl()
{
DrawMode = TabDrawMode.OwnerDrawFixed,
Parent = this,
Dock = DockStyle.Top,
};
ownerDrawFixedTabControl.DrawItem += new DrawItemEventHandler(ownerDrawFixedTabControl_DrawItem);
ownerDrawFixedTabControl.TabPages.Add(new TabPage(text));
// TabControl with Normal
var normalTabControl = new TabControl()
{
DrawMode = TabDrawMode.Normal,
Parent = this,
Dock = DockStyle.Top,
};
normalTabControl.TabPages.Add(new TabPage(text));
}
void ownerDrawFixedTabControl_DrawItem(object sender, DrawItemEventArgs e)
{
var tabControl = sender as TabControl;
var tabPage = tabControl.TabPages[e.Index];
var format = new StringFormat
{
FormatFlags = StringFormatFlags.NoWrap,
Trimming = StringTrimming.None
};
using (var brush = new SolidBrush(Color.Black))
e.Graphics.DrawString(tabPage.Text, e.Font, brush, tabControl.GetTabRect(e.Index), format);
}
}
}
Update 1 The task of "drawing text" the same way may be replaced by "measuring the text the same way". I know the size of the text I am going to draw (with either DrawString
or DrawText
) but I need to ensure the tab is wide enough. The width from TextRenderer.MeasureText
do no match the actual width of tab created.