C# label AutoSize adds padding - c#

I have a Label on a Windows.Form. I set the AutoSize property on the label to True and I noticed that when I do that, it pads the right hand side with ~5px of white background. I have the Padding property set to [0, 0, 0, 0]. Is there a way to get rid of this?
I would like to get the bounds of the label as close as possible to the text within the label.

There's no way when you use only padding and margin. That's the default behavior.
In the above Window I've set the Padding and Margin to [0,0,0,0]. Those 5 pixels are still there.
If you set FlatStyle = System and AutoSize = False you can get this:
In the above Window you don't have those 5 pixels anymore.

Ok, so FlastStyle = System; AutoSize = false; and then set up a property that will calculate the width like this:
public string LabelText
{
set
{
_label.Text = value;
using (Graphics g = CreateGraphics()) {
_label.Width = (int)g.MeasureString(_label.Text, _label.Font).Width;
}
}
}

Related

AutoSize and the Height Attribute

I am trying to auto populate some labels using a loop.
Point labelLocation = new Point(5, 15);
// e is an enum passed to the function
// box is a GroupBox passed to the function
foreach(var value in Enum.GetValues(e.GetType()))
{
Label workingLabel = new Label
{
AutoSize = true,
Location = labelLocation,
BorderStyle = BorderStyle.Fixed3D,
Text = value.ToString()
};
labelLocation = new Point(labelLocation.X, workingLabel.Location.Y + workingLabel.Height);
box.Controls.Add(workingLabel);
}
Whether or not autosize is set, the height always returns 23. So if I set autosize to false, I see borders that are too big, but nicely packed together. If I set it to true, I see borders that are perfect, except there are big gaps in between them.
It seems that the border is not the same as the height of the control, and I'm not sure how to adjust it to make them the same.
The AutoSize won't happen until the label is added to a container. So try switching the two lines of code from:
labelLocation = new Point(labelLocation.X, workingLabel.Location.Y + workingLabel.Height);
box.Controls.Add(workingLabel);
to
box.Controls.Add(workingLabel);
labelLocation = new Point(labelLocation.X, workingLabel.Location.Y + workingLabel.Height);

c# dynamically created label size not wide enough

When dynamically creating a label a part of it's text is missing. This is because the size of the label is not wide enough, it cuts of a part of the the actual string.
How do i make that simply stop? I dont want to nor do i remember setting a size to the label. Should it not just continue untill the string is empty?
Example: value = "Berserker's Iron Axe", it only displays "Berserker's Iron", because i have no size set it cust off a part of the string.
PictureBox finalResult_pBox = new PictureBox {
Name = "finalResult_pBox" + i,
Size = new Size(64, 64),
Padding = new Padding(0),
BorderStyle = BorderStyle.FixedSingle,
ImageLocation = spidyApi_idByName_result.results[i].img.ToString(),
};
MessageBox.Show(spidyApi_idByName_result.results[i].name.ToString());
Label finalResult_itemName_label = new Label{
Name = "finalResult_itemName_label" + i,
Text = spidyApi_idByName_result.results[i].name,
};
FlowLayoutPanel finalResult_panel = new FlowLayoutPanel{
FlowDirection = FlowDirection.TopDown,
BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle,
Name = "result_flowLayoutPanel" + i,
Size = new System.Drawing.Size(790, 64),
TabIndex = i,
};
finalResult_panel.Controls.Add(finalResult_pBox);
finalResult_panel.Controls.Add(finalResult_itemName_label);
result_flowLayoutPanel.Controls.Add(finalResult_panel);
Why is this happening and how do i fix this?
As long as you keep Label.AutoSize = true, which is the default it should size itself automatically.
You may want to do some tests to see the actual dimensions, like
setting a BorderStyle
or a BackColor
or inserting a space in the Text, so it gets a chance to go to a second line..
Of course you could measure the Text (with e.g. TextRenderer.MeasureText(text, Label.Font); but that will certainly not be necessary for the text simply to show.. It is useful for more demanding layout control, though.
So the first thing is to make sure that AutoSize is either true or that you measure and set the Size of the Label..

How to reduce the Default height of a group box?

I am drawing a group box at run time with dock top, and inside it I am drawing buttons of fix height and width Autosize property of group box is true. The buttons I am drawing are of less height than the default height of the group box which is acquiring at run time. How can I remove that extra lower bottom space for the group box?
GroupBox gbFreeCust = new GroupBox()
{
Dock= DockStyle.Top,
Text = item.CatName,
AutoSize = true,
AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly
};
pnlFreeCust.Controls.Add(gbFreeCust);
Try to set the Padding or the MinimumSize properties:
GroupBox gbFreeCust = new GroupBox()
{
Dock= DockStyle.Top,
Text = item.CatName,
AutoSize = true,
AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly,
Padding = new System.Windows.Forms.Padding(0),
MinimumSize = new Size(0,0)
};
pnlFreeCust.Controls.Add(gbFreeCust);

ToolStripMenuItem bigger vertical padding, or vertically centering text in a bigger ToolStripMenuItem

I'm trying to set a bigger vertical padding for ToolStripMenuItems in a ContextMenuStrip. However, changing the Padding.Top property adds padding to the bottom, instead of the top.
I also tried setting a larger Height for the ToolStripMenuItem, it works, however, the text always gets aligned on top, even if the TextAlign property is MiddleCenter. It should be vertical aligned to the center!
I've tried different settings for different properties, nothing works. The idea is that I cannot get the ToolStripMenuItem to have more space around its text, both to the top and to the bottom.
I'm using C#, Windows Forms, Net 2.0, Visual Studio 2010 Express, Windows 7.
You can get the same effect using Margin instead of Padding which will keep the Text of the ToolStripMenuItem aligned.
The drawback is that this wont modify the size of the highlight rectangle when the item is selected so it can look a little strange if you increase a lot the height.
In addition to InBetween's answer, you can fix the highlight rectangle by using a custom renderer and adjusting its "TextRectangle" property. Here's some sample code:
var itemHeight = 36;
var verticalPadding = 36 - TextRenderer.MeasureText("A", _DisplayNameFont).Height) / 2;
menu.Renderer = new MyRenderer { VerticalPadding = verticalPadding };
class MyRenderer : ToolStripSystemRenderer
{
public int VerticalPadding { get; set; }
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (null == e)
{ return; }
e.TextFormat &= ~TextFormatFlags.HidePrefix;
e.TextFormat |= TextFormatFlags.VerticalCenter;
var rect = e.TextRectangle;
rect.Offset(0, VerticalPadding);
e.TextRectangle = rect;
base.OnRenderItemText(e);
}
}
Adding a new line does the job.
It's not the best solution, but it's a quick way to add some padding.
Works well when adding support for small touch screens.
this.configToolStripMenuItem.Text = "\r\nSettings";

How do I keep a label centered in WinForms?

In WinForms I am using a Label to display different messages like success, failure, etc.
I'd like to center that label in the center form. I want a solution that will keep it centered whether there's just one word or a whole sentence in the label.
Set Label's AutoSize property to False, TextAlign property to MiddleCenter and Dock property to Fill.
You will achive it with setting property Anchor: None.
Some minor additional content for setting programmatically:
Label textLabel = new Label() {
AutoSize = false,
TextAlign = ContentAlignment.MiddleCenter,
Dock = DockStyle.None,
Left = 10,
Width = myDialog.Width - 10
};
Dockstyle and Content alignment may differ from your needs. For example, for a simple label on a wpf form I use DockStyle.None.
If you don't want to dock label in whole available area, just set SizeChanged event instead of TextChanged. Changing each letter will change the width property of label as well as its text when autosize property set to True. So, by the way you can use any formula to keep label centered in form.
private void lblReport_SizeChanged(object sender, EventArgs e)
{
lblReport.Left = (this.ClientSize.Width - lblReport.Size.Width) / 2;
}
The accepted answer didn't work for me for two reasons:
I had BackColor set so setting AutoSize = false and Dock = Fill causes the background color to fill the whole form
I couldn't have AutoSize set to false anyway because my label text was dynamic
Instead, I simply used the form's width and the width of the label to calculate the left offset:
MyLabel.Left = (this.Width - MyLabel.Width) / 2;
I wanted to do something similar, but on a form with a background image, I found that when the text in the label changed the repaints were obvious with this method, so I did the following:
* Set the label AutoSize to true and TextAlign to MiddleCenter
Then, each time the text changed (mine was done using a timer) I called the following method:
private Point GetPosition()
{
int y = (this.Height / 2) - (label1.Height / 2);
int x = (this.Width / 2) - (label1.Width / 2);
return new Point(x, y);
}
And set the label's Location property to this return value. This ensured that the label was always in the center of the form when the text changed and the repaints for a full-screen form weren't obvious.
You could try out the following code snippet:
private Point CenterOfMenuPanel<T>(T control, int height=0) where T:Control {
Point center = new Point(
MenuPanel.Size.Width / 2 - control.Width * 2,
height != 0 ? height : MenuPanel.Size.Height / 2 - control.Height / 2);
return center;
}
It's Really Center

Categories

Resources