How to move a control to the center of the screen at runtime in C #?

So, I have a control (this is a shortcut) of different sizes. I want to re-place it in the form every time it changes (horizontally, not vertically). How to do this programmatically?

+4
source share
4 answers
YourLabel.Left = (YourForm.Width / 2) - (YourLabel.Width / 2); 

If you want this to be adjusted every time the form is resized, just use the Form.Resize event.

+7
source

No code required: AutoSize = False, TextAlign = TopCenter. Make it as big as you allow. An anchor on the right is optional.

+4
source

The easiest way to center any component. may be helpful to someone. Right click on Project β†’ Add β†’ Class

Update this class with the code below.

 public static class MyClass { public static void center(this Control component) { float compWidth = component.Width; float parentWidth = component.Parent.Width; float middled = (parentWidth / 2) - (compWidth / 2); component.Left = Convert.ToInt32(middled); } } 

and then you can cut any component. you can use any component like this

 MyLabel.center(); MyPanel.center(); 
+1
source

Okay, so I'm standing fixed - thanks guys.

Here is a workaround to do this without code using RAD (development time). Note. I would go with @Shark's answer as I don't think this will produce the result after, but here it is:

  • Drop the button in the form

  • Set text as text in label

  • Size button for text

  • In the properties of the buttons "FlatStlye = Flat"

  • In the properties of the buttons, expand "Flat appearance" and set the frame size = 0

  • Now set the snap left and right

0
source

Source: https://habr.com/ru/post/1393895/


All Articles