Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a label on any form VB.NET

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.

like image 628
soulblazer Avatar asked Dec 22 '14 23:12

soulblazer


2 Answers

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

like image 51
Jens Avatar answered Oct 06 '22 13:10

Jens


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.

like image 5
VBNETcoder Avatar answered Oct 06 '22 11:10

VBNETcoder