Use Form.CenterToScreen() method.
Using the Property window
Select form → go to property window → select "start position" → select whatever the place you want.
Programmatically
Form form1 = new Form();
form1.StartPosition = FormStartPosition.CenterScreen;
form1.ShowDialog();
Note: Do not directly call Form.CenterToScreen() from your code. Read here.
A single line:
this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
In Windows Forms:
this.StartPosition = FormStartPosition.CenterScreen;
In WPF:
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
That's all you have to do...
If you want to center your windows during runtime use the code below, copy it into your application:
protected void ReallyCenterToScreen()
{
Screen screen = Screen.FromControl(this);
Rectangle workingArea = screen.WorkingArea;
this.Location = new Point() {
X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}
And finally call the method above to get it working:
ReallyCenterToScreen();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With