Center a label on any form VB.NET
Asked Answered
W

2

6

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.

Warmblooded answered 22/12, 2014 at 23:14 Comment(1)
That equation wont give you anything that knows it is equidistant from the edges of the form. You need to place the label centrepoint at Form1.Width/2.Wadleigh
M
17

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

Moonstone answered 22/12, 2014 at 23:42 Comment(2)
Now it's properly centered! Thank you!Warmblooded
You are welcome. I added some additional explaination as well.Moonstone
A
6

Here is a more professional solution:

horizontal centering:

 myLabel.Left = (myLabel.Parent.Width \2) - (myLabel.Width \2)

vertical centering:

myLabel.Top = (myLabel.Parent.Height \ 2) - (myLabel.Height \ 2)

add this code on the myLabel.[SizeChanged][1] Event handler as well as on its parent SizeChanged Event handler

p.s. dont add the codeline before the InitializeComponent() method is called or before the control being attached to a parent control.

Abbey answered 28/1, 2016 at 22:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.