Measure width of numbers in Bitmaps - c#

I created a texture (bitmap) that is used for drawing arbitrary numbers
The texture contains the text: 0123456789.-
Now I need the coordinates of each character.
TextRenderer.MeasureText(c.ToString(), m_font, new Size(1, 1), TextFormatFlags.NoPadding);
...returns is 16x17
g.MeasureString(c.ToString(), m_font);
...returns is 11.9x17.7
The actual size is 8x11
My workaround for now is a manual measurement of each character which yields the following table:
coords.Add('0', new RectangleF(1, 3, 8, 11));
coords.Add('1', new RectangleF(9, 3, 7, 11));
coords.Add('2', new RectangleF(15, 3, 8, 11));
coords.Add('3', new RectangleF(22, 3, 8, 11));
coords.Add('4', new RectangleF(29, 3, 8, 11));
coords.Add('5', new RectangleF(36, 3, 8, 11));
coords.Add('6', new RectangleF(43, 3, 8, 11));
coords.Add('7', new RectangleF(50, 3, 8, 11));
coords.Add('8', new RectangleF(57, 3, 8, 11));
coords.Add('9', new RectangleF(64, 3, 8, 11));
coords.Add('.', new RectangleF(72, 3, 3, 11));
coords.Add('-', new RectangleF(75, 3, 6, 11));
I would like to use a dynamic font, so a programmatic way to measure the size is required.

Tell the MeasureString method to work with the generic typographic StringFormat.
static void Main(string[] args)
{
var image = new Bitmap(1000, 500);
var g = Graphics.FromImage(image);
g.FillRectangle(System.Drawing.Brushes.White, 0, 0, 1000, 500);
var stringFormat = new StringFormat(StringFormat.GenericTypographic) {
Alignment = StringAlignment.Near,
FormatFlags = System.Drawing.StringFormatFlags.LineLimit | System.Drawing.StringFormatFlags.NoClip | StringFormatFlags.DirectionRightToLeft
};
var font = new Font(new System.Drawing.FontFamily("Times New Roman"), 72.0f,FontStyle.Regular, GraphicsUnit.Point);
var point = new PointF { X = 10, Y = 10 };
SizeF[] outputs = new SizeF[7];
SizeF[] total = new SizeF[7];
outputs[0] = g.MeasureString("T", font, point, stringFormat);
outputs[1] = g.MeasureString("e", font, point, stringFormat);
outputs[2] = g.MeasureString("s", font, point, stringFormat);
outputs[3] = g.MeasureString("t", font, point, stringFormat);
outputs[4] = g.MeasureString("S", font, point, stringFormat);
outputs[5] = g.MeasureString("t", font, point, stringFormat);
outputs[6] = g.MeasureString("r", font, point, stringFormat);
total[0] = g.MeasureString("T", font, point, stringFormat);
total[1] = g.MeasureString("Te", font, point, stringFormat);
total[2] = g.MeasureString("Tes", font, point, stringFormat);
total[3] = g.MeasureString("Test", font, point, stringFormat);
total[4] = g.MeasureString("TestS", font, point, stringFormat);
total[5] = g.MeasureString("TestSt", font, point, stringFormat);
total[6] = g.MeasureString("TestStr", font, point, stringFormat);
stringFormat.FormatFlags = System.Drawing.StringFormatFlags.LineLimit | System.Drawing.StringFormatFlags.NoClip;
g.DrawString("TestStr", font, System.Drawing.Brushes.Red, new PointF { X = 10, Y = 10 }, stringFormat);
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue, 1.0f), GetOutputPositionX(total,outputs, 0), 10.0f, outputs[0].Width, outputs[0].Height);
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue, 1.0f), GetOutputPositionX(total,outputs, 1), 10.0f, outputs[1].Width, outputs[1].Height);
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue, 1.0f), GetOutputPositionX(total,outputs, 2), 10.0f, outputs[2].Width, outputs[2].Height);
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue, 1.0f), GetOutputPositionX(total,outputs, 3), 10.0f, outputs[3].Width, outputs[3].Height);
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue, 1.0f), GetOutputPositionX(total,outputs, 4), 10.0f, outputs[4].Width, outputs[4].Height);
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue, 1.0f), GetOutputPositionX(total,outputs, 5), 10.0f, outputs[5].Width, outputs[5].Height);
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue, 1.0f), GetOutputPositionX(total,outputs, 6), 10.0f, outputs[6].Width, outputs[6].Height);
image.Save(#"c:\Temp\bla.png");
}
private static float GetOutputPositionX(SizeF[] total, SizeF[] outputs, int p)
{
return 10.0f + total[p].Width - outputs[p].Width;
}
To get the Position exactly, because of these overlapping characters you have to calculate the width of "e" and the total width of "Te".
Plus there is obviously a bug in the MeasureString function. If you call MeasureString without the StringFormatFlags.DirectionRightToLeft the overlap of the characters "Te" is ignored.

Related

Printing a Multi-page Listview

Ok, I have got a printDocument1_PrintPage method which is supposed to print out the contents of a ListView. During execution, the method only prints out the first page. Could someone help me to printout the remaining page(s)?
I have identified the end of the first page via the variable ypos and set the property e.HasMorePages = true.
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e){
Graphics graphics = e.Graphics;
int ypos = 78;
Font f1 = new Font("Arial", 14, FontStyle.Bold, GraphicsUnit.Pixel);
Brush brush = new SolidBrush(Color.LightSlateGray);
graphics.FillRectangle(brush, new Rectangle(10, 10, 770, 50));
Pen blackpen = new Pen(Color.Black);
Pen graypen = new Pen(Color.LightGray);
Pen redpen = new Pen(Color.Red);
graphics.DrawRectangle(blackpen, new Rectangle(10, 10, 770, 50));
Brush B = new SolidBrush(listView1.ForeColor);
graphics.DrawLine(blackpen, 10, 10, 10, 1132);
graphics.DrawString("FORENAME", f1, Brushes.Black, new Point(20, 25));
graphics.DrawLine(blackpen, 130, 10, 130, 1132);
graphics.DrawString("SURNAME", f1, Brushes.Black, new Point(140, 25));
graphics.DrawLine(blackpen, 290, 10, 290, 1132);
graphics.DrawString("EXT.", f1, Brushes.Black, new Point(300, 25));
graphics.DrawLine(blackpen, 380, 10, 380, 1132);
graphics.DrawString("JOB TITLE", f1, Brushes.Black, new Point(410, 25));
graphics.DrawLine(blackpen, 780, 10, 780, 1132);
int[] X = { 15, 140, 300, 390, 720 };
int Y = 60;
f1 = listView1.Font;
for (int I = 0; I < listView1.Items.Count; I++){
for (int J = 0; J < listView1.Items[I].SubItems.Count - 1; J++){
graphics.DrawString(listView1.Items[I].SubItems[J].Text, f1, B, X[J], Y);
}
Y += f1.Height;
graphics.DrawLine(graypen, 10, ypos, 780, ypos);
ypos = ypos + 17;
if (ypos > 1132){
e.HasMorePages = true;
return;
}
}
graphics.Dispose();
}

Print data grid view data in two printer?

I want to print some data in printer 1 and some data in printer 2.
public void printkot()
{
PrintDialog pd = new PrintDialog();
PrintDocument pdoc = new PrintDocument();
PrinterSettings ps = new PrinterSettings();
Font font = new Font("Arial", 12);
PaperSize psize = new PaperSize("Custome", 314, 500);
pd.Document = pdoc;
for (int ch = 0; dataGridView1.Rows.Count > ch; ch++)
{
if (dataGridView1.Rows[ch].Cells["calkot_print"].Value.ToString() == "K1")
{
pdoc.PrinterSettings.PrinterName = "KOT";
pdoc.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
}
}
pd.Document.DefaultPageSettings.PaperSize = psize;
pdoc.DefaultPageSettings.PaperSize.Height = 500;
pdoc.DefaultPageSettings.PaperSize.Width = 314;
if (pdoc.PrinterSettings.IsValid)
{
pdoc.Print();
}
else
{
MessageBox.Show("Printer is invalid.");
}
}
private void printDocument1_PrintPage2(object sender, PrintPageEventArgs e)
{
string table_no;
table_no = lbltable.Text;
float xs = 10;
float ys = 5;
float widths = 285.0F; // max width I found through trial and error
float heights = 0F;
DataTable dtm = blu.checkbusiness();
Font drawFontArial12Bold = new Font("Arial", 12, FontStyle.Bold);
Font drawFontArial10Regular = new Font("Arial", 9, FontStyle.Regular);
Font drawFontArial10Regularsmall = new Font("Arial", 6, FontStyle.Regular);
SolidBrush drawBrush = new SolidBrush(Color.Black);
Pen drawingPen = new Pen(Color.Black, 1);
// Set format of string.
StringFormat drawFormatCenter = new StringFormat();
drawFormatCenter.Alignment = StringAlignment.Center;
StringFormat drawFormatLeft = new StringFormat();
drawFormatLeft.Alignment = StringAlignment.Near;
StringFormat drawFormatRight = new StringFormat();
drawFormatRight.Alignment = StringAlignment.Far;
StringFormat drawFormatRightlest = new StringFormat();
string business_name = dtm.Rows[0]["business_name"].ToString();
string address = dtm.Rows[0]["address"].ToString();
Graphics gra = e.Graphics;
String strDate = DateTime.Now.ToLongTimeString();
gra.DrawString(strDate, new System.Drawing.Font("Arial", 7, FontStyle.Regular), new SolidBrush(System.Drawing.Color.Black), 10, 60);
e.Graphics.DrawString(business_name, drawFontArial12Bold, drawBrush, new RectangleF(xs, ys, widths, heights), drawFormatCenter);
ys += e.Graphics.MeasureString(business_name, drawFontArial12Bold).Height;
e.Graphics.DrawString(address, drawFontArial10Regular, drawBrush, new RectangleF(xs, ys, widths, heights), drawFormatCenter);
ys += e.Graphics.MeasureString(address, drawFontArial10Regular).Height;
gra.DrawString("Table No::", new System.Drawing.Font("Arial", 9, FontStyle.Regular), new SolidBrush(System.Drawing.Color.Black), 190, 60);
gra.DrawString(table_no, new System.Drawing.Font("Arial", 9, FontStyle.Regular), new SolidBrush(System.Drawing.Color.Black), 250, 45);
gra.DrawLine(drawingPen, 10, 75, 309, 75);
gra.DrawString("Item", new System.Drawing.Font("Arial", 9, FontStyle.Bold), new SolidBrush(System.Drawing.Color.Black), 30, 75);
gra.DrawString("Qty", new System.Drawing.Font("Arial", 9, FontStyle.Bold), new SolidBrush(System.Drawing.Color.Black), 220, 75);
gra.DrawLine(drawingPen, 10, 90, 309, 90);
int y;
y = 95;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string item_name = dataGridView1.Rows[i].Cells["cal_item_name"].Value.ToString();
string quantity = dataGridView1.Rows[i].Cells["cal_qty"].Value.ToString();
if (dataGridView1.Rows[i].Cells["calkot_print"].Value.ToString() == "K2")
{
gra.DrawString(item_name.ToString(), new System.Drawing.Font("Time New Roamn", 9, FontStyle.Regular), new SolidBrush(System.Drawing.Color.Black), 30, y);
gra.DrawString(quantity, new System.Drawing.Font("Time New Roamn", 9, FontStyle.Regular), new SolidBrush(System.Drawing.Color.Black), 220, y);
y = y + 15;
}
}
int z = y + 20;
gra.DrawLine(drawingPen, 10, z, 309, z);
gra.DrawString("Description", new System.Drawing.Font("Time New Roamn", 9, FontStyle.Bold), new SolidBrush(System.Drawing.Color.Black), 10, z + 5);
gra.DrawString(txtrichbox.Text, new System.Drawing.Font("Time New Roamn", 7, FontStyle.Regular), new SolidBrush(System.Drawing.Color.Black), 10, z + 20);
z = y + 20;
}

Lost trying to draw a line of x length y degrees

I think its my maths that's letting me down!
I'm trying to draw a line of x length at Y degrees on a picturebox control with a North South East west, lines.
the below works but draws the line line at 250 degrees not 290!?
Bitmap bmp = new Bitmap(400, 400);
Graphics g = Graphics.FromImage(bmp);
// smooth graphics
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawLine(new Pen(Color.Black, 2), 205, 20, 205, 385);
g.DrawLine(new Pen(Color.Red, 2), 20, 205, 390, 205);
// let's draw a coordinate equivalent to (20,30) (20 up, 30 across)
g.DrawString("N", new Font("Calibri", 12 , FontStyle.Bold), new SolidBrush(Color.Black), 197, 0);
g.DrawString("S", new Font("Calibri", 12, FontStyle.Bold), new SolidBrush(Color.Black), 197, 385);
g.DrawString("W", new Font("Calibri", 12, FontStyle.Bold), new SolidBrush(Color.Black), 0, 195);
g.DrawString("E", new Font("Calibri", 12, FontStyle.Bold), new SolidBrush(Color.Black), 390, 195);
//Draw Wind line
int x = 205, y = 205;
int wSpeed = 30*3; //length of line
int angle = 290; //angle to draw line at.
int startX = x;
int startY = y;
int endX = Convert.ToInt32(Math.Round(x + wSpeed * Math.Sin(Calcs.Radians(angle))));
int endY = Convert.ToInt32(Math.Round(y + wSpeed * Math.Cos(Calcs.Radians(angle))));
g.DrawLine(new Pen(Color.Blue, 2), startX, startY, endX, endY);
PictureBox display = pictureBox1;
this.Controls.Add(display);
display.Image = bmp;
public static double Radians(double dDegrees)
{
double result = Math.PI * dDegrees / 180.0;
return result;
}
If you look at the results: its -20 degrees from 270, instead of +20 expected, meaning you v got correct Y but wrong X. I suggest check(change) the sign of X coord. Graphics is very often trial-error unless you are expert.
int endX = Convert.ToInt32(Math.Round(x - wSpeed * Math.Sin(Calcs.Radians(angle))));

C# how to paint User Control with background Transparency

I'd like to know how to paint User Control with background Transparency even if the user control is raised or moved at runtime.
my code is
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
g.Clear(Color.White);
g.SmoothingMode = SmoothingMode.HighQuality;//可以反锯齿
var rectBound = new Rectangle(0, 0, Width-1, Height-1);
var b = new SolidBrush(Color.FromArgb(0, 122, 204));
var rect = new Rectangle(2, 2, Width - 4, Height - 4);
if(!_isSelected)//FillRectangle
g.FillEllipse(b, rectBound);
else
g.FillEllipse(b, rect);
var pen = new Pen(Color.Yellow);
pen.DashStyle = DashStyle.DashDot;
g.DrawLine(pen,10,10,100,10);
pen.DashStyle = DashStyle.Dash;
g.DrawLine(pen, 10, 15, 100, 15);
pen.DashStyle = DashStyle.DashDotDot;
g.DrawLine(pen, 10, 20, 100, 20);
pen.DashStyle = DashStyle.Dot;
g.DrawLine(pen, 10, 25, 100, 25);
pen.DashStyle = DashStyle.Solid;
g.DrawLine(pen, 10, 30, 100, 30);
if (_isSelected)
{
pen = new Pen(Color.Black) { DashStyle = DashStyle.Dot, Width = 1 };
g.DrawRectangle(pen, rectBound);
}
}
and demo picture here
there will be a lot of User Controls Created at runtime,some of them maybe overlapped,then it should be clear the user control's background.how to do that?

Vertical Tab Control with horizontal text in Winforms

I would like to have the tabs on my TabControl displayed on the left, or sometimes right.
Unlike the System.Windows.Forms.TabControl, however, I would like the text to remain horizontal instead of being rotated by 90 or 270 degrees to the horizontal.
Here are a couple of pictures illustrating the concept
Though I could write code to do this myself in about an hour or two, I just thought I'd ask first if there is any existing Winforms control that implements such feature.
NB: Any existing solution should preferably be non-commercial.
Thanks.
I don't know how robust this is and I can't claim to have created it but...
http://www.dreamincode.net/forums/topic/125792-how-to-make-vertical-tabs/
Here's a way of doing it.
So first we are going to change its alignment to Left, by setting the property:
Alignment = Left
If you have XP themes turned on then you may notice the weird layout of Tab Control. Don't worry we will make it fine.
As you may have noticed that Tabs are vertical, and our requirement is horizontal. So we can change the size of Tabs. But before we can do this we have to set the SizeMode property as,
SizeMode = Fixed
Now we can change the size by using the ItemSize property,
ItemSize = 30, 120
Width = 30 and Height = 120
After setting the Alignment = Left, Tab control rotates the Tabs which causes the Width and Height seem to be reversed. That is why when we increase Height, we see that width is increasing and when we increase width the height is effected.
Now Text will also be displaying, but vertically. Unfortunately there is no simple way to resolve this issue. For this purpose we have to write the Text by ourselves. To do this we will first set the DrawMode
DrawMode = OwnerDrawFixed
01
Private Sub TabControl1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem
Dim g As Graphics
Dim sText As String
Dim iX As Integer
Dim iY As Integer
Dim sizeText As SizeF
Dim ctlTab As TabControl
ctlTab = CType(sender, TabControl)
g = e.Graphics
sText = ctlTab.TabPages(e.Index).Text
sizeText = g.MeasureString(sText, ctlTab.Font)
iX = e.Bounds.Left + 6
iY = e.Bounds.Top + (e.Bounds.Height - sizeText.Height) / 2
g.DrawString(sText, ctlTab.Font, Brushes.Black, iX, iY)
End Sub
This is the code for a custom tab control that I'm quite fond of. You will need to copy and paste this code into a new class then rebuild the project. You will see a new custom user control displayed in your toolbox.
Imports System.Drawing.Drawing2D
Class DotNetBarTabcontrol
Inherits TabControl
Sub New()
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint Or ControlStyles.DoubleBuffer, True)
DoubleBuffered = True
SizeMode = TabSizeMode.Fixed
ItemSize = New Size(44, 136)
End Sub
Protected Overrides Sub CreateHandle()
MyBase.CreateHandle()
Alignment = TabAlignment.Left
End Sub
Function ToPen(ByVal color As Color) As Pen
Return New Pen(color)
End Function
Function ToBrush(ByVal color As Color) As Brush
Return New SolidBrush(color)
End Function
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
Dim B As New Bitmap(Width, Height)
Dim G As Graphics = Graphics.FromImage(B)
Try : SelectedTab.BackColor = Color.White : Catch : End Try
G.Clear(Color.White)
G.FillRectangle(New SolidBrush(Color.FromArgb(246, 248, 252)), New Rectangle(0, 0, ItemSize.Height + 4, Height))
'G.DrawLine(New Pen(Color.FromArgb(170, 187, 204)), New Point(Width - 1, 0), New Point(Width - 1, Height - 1)) 'comment out to get rid of the borders
'G.DrawLine(New Pen(Color.FromArgb(170, 187, 204)), New Point(ItemSize.Height + 1, 0), New Point(Width - 1, 0)) 'comment out to get rid of the borders
'G.DrawLine(New Pen(Color.FromArgb(170, 187, 204)), New Point(ItemSize.Height + 3, Height - 1), New Point(Width - 1, Height - 1)) 'comment out to get rid of the borders
G.DrawLine(New Pen(Color.FromArgb(170, 187, 204)), New Point(ItemSize.Height + 3, 0), New Point(ItemSize.Height + 3, 999))
For i = 0 To TabCount - 1
If i = SelectedIndex Then
Dim x2 As Rectangle = New Rectangle(New Point(GetTabRect(i).Location.X - 2, GetTabRect(i).Location.Y - 2), New Size(GetTabRect(i).Width + 3, GetTabRect(i).Height - 1))
Dim myBlend As New ColorBlend()
myBlend.Colors = {Color.FromArgb(232, 232, 240), Color.FromArgb(232, 232, 240), Color.FromArgb(232, 232, 240)}
myBlend.Positions = {0.0F, 0.5F, 1.0F}
Dim lgBrush As New LinearGradientBrush(x2, Color.Black, Color.Black, 90.0F)
lgBrush.InterpolationColors = myBlend
G.FillRectangle(lgBrush, x2)
G.DrawRectangle(New Pen(Color.FromArgb(170, 187, 204)), x2)
G.SmoothingMode = SmoothingMode.HighQuality
Dim p() As Point = {New Point(ItemSize.Height - 3, GetTabRect(i).Location.Y + 20), New Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + 14), New Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + 27)}
G.FillPolygon(Brushes.White, p)
G.DrawPolygon(New Pen(Color.FromArgb(170, 187, 204)), p)
If ImageList IsNot Nothing Then
Try
If ImageList.Images(TabPages(i).ImageIndex) IsNot Nothing Then
G.DrawImage(ImageList.Images(TabPages(i).ImageIndex), New Point(x2.Location.X + 8, x2.Location.Y + 6))
G.DrawString(" " & TabPages(i).Text, Font, Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
Else
G.DrawString(TabPages(i).Text, New Font(Font.FontFamily, Font.Size, FontStyle.Bold), Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
End If
Catch ex As Exception
G.DrawString(TabPages(i).Text, New Font(Font.FontFamily, Font.Size, FontStyle.Bold), Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
End Try
Else
G.DrawString(TabPages(i).Text, New Font(Font.FontFamily, Font.Size, FontStyle.Bold), Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
End If
G.DrawLine(New Pen(Color.FromArgb(200, 200, 250)), New Point(x2.Location.X - 1, x2.Location.Y - 1), New Point(x2.Location.X, x2.Location.Y))
G.DrawLine(New Pen(Color.FromArgb(200, 200, 250)), New Point(x2.Location.X - 1, x2.Bottom - 1), New Point(x2.Location.X, x2.Bottom))
Else
Dim x2 As Rectangle = New Rectangle(New Point(GetTabRect(i).Location.X - 2, GetTabRect(i).Location.Y - 2), New Size(GetTabRect(i).Width + 3, GetTabRect(i).Height + 1))
G.FillRectangle(New SolidBrush(Color.FromArgb(246, 248, 252)), x2)
G.DrawLine(New Pen(Color.FromArgb(170, 187, 204)), New Point(x2.Right, x2.Top), New Point(x2.Right, x2.Bottom))
If ImageList IsNot Nothing Then
Try
If ImageList.Images(TabPages(i).ImageIndex) IsNot Nothing Then
G.DrawImage(ImageList.Images(TabPages(i).ImageIndex), New Point(x2.Location.X + 8, x2.Location.Y + 6))
G.DrawString(" " & TabPages(i).Text, Font, Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
Else
G.DrawString(TabPages(i).Text, Font, Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
End If
Catch ex As Exception
G.DrawString(TabPages(i).Text, Font, Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
End Try
Else
G.DrawString(TabPages(i).Text, Font, Brushes.DimGray, x2, New StringFormat With {.LineAlignment = StringAlignment.Center, .Alignment = StringAlignment.Center})
End If
End If
Next
e.Graphics.DrawImage(B.Clone, 0, 0)
G.Dispose() : B.Dispose()
End Sub
End Class
This is an old question but I found a good looking C# class. After adding the normal WinForms tab control. Add this to your project as a class E.G DotNetBarTabControl.cs Then make sure to replace the Winforms tab controls to this class.
this.tabControl1 = new System.Windows.Forms.TabControl();
must be changed to:
this.tabControl1 = new TabControls.DotNetBarTabControl();
private System.Windows.Forms.TabControl tabControl1;
must be changed to:
private TabControls.DotNetBarTabControl tabControl1;
DotNetBarTabControl.cs Class:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
// thanks to Mavamaarten~ for coding this
namespace TabControls
{
internal class DotNetBarTabControl : TabControl
{
public DotNetBarTabControl()
{
SetStyle(
ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint |
ControlStyles.DoubleBuffer, true);
SizeMode = TabSizeMode.Fixed;
ItemSize = new Size(44, 136);
Alignment = TabAlignment.Left;
SelectedIndex = 0;
}
protected override void OnPaint(PaintEventArgs e)
{
Bitmap b = new Bitmap(Width, Height);
Graphics g = Graphics.FromImage(b);
if (!DesignMode)
SelectedTab.BackColor = SystemColors.Control;
g.Clear(SystemColors.Control);
g.FillRectangle(new SolidBrush(Color.FromArgb(246, 248, 252)),
new Rectangle(0, 0, ItemSize.Height + 4, Height));
g.DrawLine(new Pen(Color.FromArgb(170, 187, 204)), new Point(ItemSize.Height + 3, 0),
new Point(ItemSize.Height + 3, 999));
g.DrawLine(new Pen(Color.FromArgb(170, 187, 204)), new Point(0, Size.Height - 1),
new Point(Width + 3, Size.Height - 1));
for (int i = 0; i <= TabCount - 1; i++)
{
if (i == SelectedIndex)
{
Rectangle x2 = new Rectangle(new Point(GetTabRect(i).Location.X - 2, GetTabRect(i).Location.Y - 2),
new Size(GetTabRect(i).Width + 3, GetTabRect(i).Height - 1));
ColorBlend myBlend = new ColorBlend();
myBlend.Colors = new Color[] { Color.FromArgb(232, 232, 240), Color.FromArgb(232, 232, 240), Color.FromArgb(232, 232, 240) };
myBlend.Positions = new float[] { 0f, 0.5f, 1f };
LinearGradientBrush lgBrush = new LinearGradientBrush(x2, Color.Black, Color.Black, 90f);
lgBrush.InterpolationColors = myBlend;
g.FillRectangle(lgBrush, x2);
g.DrawRectangle(new Pen(Color.FromArgb(170, 187, 204)), x2);
g.SmoothingMode = SmoothingMode.HighQuality;
Point[] p =
{
new Point(ItemSize.Height - 3, GetTabRect(i).Location.Y + 20),
new Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + 14),
new Point(ItemSize.Height + 4, GetTabRect(i).Location.Y + 27)
};
g.FillPolygon(SystemBrushes.Control, p);
g.DrawPolygon(new Pen(Color.FromArgb(170, 187, 204)), p);
if (ImageList != null)
{
try
{
g.DrawImage(ImageList.Images[TabPages[i].ImageIndex],
new Point(x2.Location.X + 8, x2.Location.Y + 6));
g.DrawString(" " + TabPages[i].Text, Font, Brushes.Black, x2, new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
});
}
catch (Exception)
{
g.DrawString(TabPages[i].Text, new Font(Font.FontFamily, Font.Size, FontStyle.Bold),
Brushes.Black, x2, new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
});
}
}
else
{
g.DrawString(TabPages[i].Text, new Font(Font.FontFamily, Font.Size, FontStyle.Bold),
Brushes.Black, x2, new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
});
}
g.DrawLine(new Pen(Color.FromArgb(200, 200, 250)), new Point(x2.Location.X - 1, x2.Location.Y - 1),
new Point(x2.Location.X, x2.Location.Y));
g.DrawLine(new Pen(Color.FromArgb(200, 200, 250)), new Point(x2.Location.X - 1, x2.Bottom - 1),
new Point(x2.Location.X, x2.Bottom));
}
else
{
Rectangle x2 = new Rectangle(new Point(GetTabRect(i).Location.X - 2, GetTabRect(i).Location.Y - 2),
new Size(GetTabRect(i).Width + 3, GetTabRect(i).Height - 1));
g.FillRectangle(new SolidBrush(Color.FromArgb(246, 248, 252)), x2);
g.DrawLine(new Pen(Color.FromArgb(170, 187, 204)), new Point(x2.Right, x2.Top),
new Point(x2.Right, x2.Bottom));
if (ImageList != null)
{
try
{
g.DrawImage(ImageList.Images[TabPages[i].ImageIndex],
new Point(x2.Location.X + 8, x2.Location.Y + 6));
g.DrawString(" " + TabPages[i].Text, Font, Brushes.DimGray, x2, new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
});
}
catch (Exception)
{
g.DrawString(TabPages[i].Text, Font, Brushes.DimGray, x2, new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
});
}
}
else
{
g.DrawString(TabPages[i].Text, Font, Brushes.DimGray, x2, new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
});
}
}
}
e.Graphics.DrawImage(b, new Point(0, 0));
g.Dispose();
b.Dispose();
}
}
}
You can have fun making a dark theme to. In the photo Form2 uses the material skin. It can be found on NuGet as well.
I have decided to share the code I developed since some people, such as Amit Andharia, would like to benefit from it.
This is the result after I had implemented Rob P.'s answer.
Release Notes:
Full design time support
Automatic resizing of tabs (up to 128px wide)
Tab icons implemented
Unused properties have been hidden
The code can be downloaded from here.
There is a tutorial provided by Microsoft for doing this with the existing TabControl on MSDN, with sample code given in both C# and Visual Basic .NET. Their method is based on using owner drawing. Summarizing their steps below:
Set the TabControl's Alignment property to Right.
Ensure all tabs are the same horizontal width by setting the SizeMode property to Fixed.
Set the ItemSize property to your preferred size for the tabs, keeping in mind that the width and height are reversed.
Set the DrawMode property to OwnerDrawFixed.
Set up an event handler for the TabControl's DrawItem event, and place your owner drawing code in there dictating how each tab should be displayed. Their C# sample code for the event handler is reproduced below for convenience (it assumes your TabControl is named tabControl1:
private void tabControl1_DrawItem(Object sender, System.Windows.Forms.DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Brush _textBrush;
// Get the item from the collection.
TabPage _tabPage = tabControl1.TabPages[e.Index];
// Get the real bounds for the tab rectangle.
Rectangle _tabBounds = tabControl1.GetTabRect(e.Index);
if (e.State == DrawItemState.Selected)
{
// Draw a different background color, and don't paint a focus rectangle.
_textBrush = new SolidBrush(Color.Red);
g.FillRectangle(Brushes.Gray, e.Bounds);
}
else
{
_textBrush = new System.Drawing.SolidBrush(e.ForeColor);
e.DrawBackground();
}
// Use our own font.
Font _tabFont = new Font("Arial", (float)10.0, FontStyle.Bold, GraphicsUnit.Pixel);
// Draw string. Center the text.
StringFormat _stringFlags = new StringFormat();
_stringFlags.Alignment = StringAlignment.Center;
_stringFlags.LineAlignment = StringAlignment.Center;
g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
}
You can probably experiment with your ItemSize property and the _tabFont value from the above code to fine-tune your tabs' appearance to whatever you need. For even fancier styling, I'd recommend looking at this other MSDN article as a starting point.
(Source: How to: Display Side-Aligned Tabs with TabControl (MSDN))

Categories