Center a label on any form VB.NET

soulblazer picture soulblazer · Dec 23, 2014 · Viewed 29.3k times · Source

I need to show a form with a centered label (according to form's width and label's text, width, font family and font size). This have been my attempt so far:

(Me.Width - TextRenderer.MeasureText("Hello word", New Font("Delius", 10, 
FontStyle.Regular).Width) / 2

No matter how much I try, the label doesn't appear centered as it should (label's left and right sides don't appear to be the same size).

Is there another way to measure text no matter which font is used? Thank you.

Answer

Jens picture Jens · Dec 23, 2014

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.

The Anchor property is pretty nifty, because it basically pins the a border of a control to the respective side of the form.
So in our case the left side of the control sticks to the left side of the form, and the right side sticks to the right side of the form.
So if the form is resized, it drags the left and right side of the control with it. Together with the TextAlign, this always keeps the text centered.
For this to work, the AutoSize functionality of the label needs to be disabled.

An alternative way would be to keep AutoSize enabled, center the form on the control, and then disable both Left and Right Anchor. This would keep the label centered as well, as it now does no longer stick to either side but keeps its relative position.

So: Let the control do the work for you.

enter image description here