0

I have no idea why this is difficult to find out how to do. It baffles me.

Say I have a button inside the form. I want on form load for the buttons position from top to be form height/2 - button height/2 and position from left to be form width/2 - button width/2.

Or any other way of making it central...

maxisme
  • 3,974
  • 9
  • 47
  • 97

5 Answers5

0

Assuming your button is named button1 and your Form form1:

button1.Location.X = (form1.Width / 2) - (button1.Width / 2);
button1.Location.Y = (form1.Height / 2) - (button1.Height/ 2);

Disclaimer: untested

maxisme
  • 3,974
  • 9
  • 47
  • 97
mnme
  • 620
  • 6
  • 19
0

If I am not mistaken what you are looking is Docking.

I think that your question is answer here How to dock a windows form in C#?

Community
  • 1
  • 1
Gregorjo
  • 1
  • 2
0

In design time, go to menu Format > Center in form and center your button. Then remove all the anchors for this button. This will keep in the center.

Marko Juvančič
  • 5,792
  • 1
  • 25
  • 41
0

This how to do it if the object is named groupBox1:

int X = (this.Width / 2) - (groupBox1.Width / 2);
int Y = (this.Height / 2) - (groupBox1.Height / 2);
groupBox1.Location = new Point(X, Y);
maxisme
  • 3,974
  • 9
  • 47
  • 97
0

Other way of making it central

Add TableLayoutPanel to a form, make its Dock = Fill. Add 3 rows and 3 columns. Drop your button into a middle cell. Make middle cell type AutoSize (row and column). Make others columns and rows type Percent and enter 50 there.

Whenever you resize the form, TableLayoutPanel will layout your button in the middle.

Sinatr
  • 20,892
  • 15
  • 90
  • 319