Set the Autosize property of your label to False, then either Dock the Label Top, Bottom or Fill, or drag it to the full width of the form and set Anchor to both Left and Right. Then set TextAlign to MiddleCenter.
Use Form. CenterToScreen() method. On system with two monitors the form will be centered on one that currently have the cursor.
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:
BackColor
set so setting AutoSize = false
and Dock = Fill
causes the background color to fill the whole formAutoSize
set to false anyway because my label text was dynamicInstead, 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With