I create a new form and call from the parent form as follows:
loginForm = new SubLogin();
loginForm.Show();
I need to display the child form at the centre of the parent. So,in the child form load I do the foll:`
Point p = new Point(this.ParentForm.Width / 2 - this.Width / 2, this.ParentForm.Height / 2 - this.Height / 2);
this.Location = p;
But this is throwing error as parent form is null. I tried setting the Parent property as well, but didn't help. Any inputs on this?
If you have to center your childForm, from childForm then the code will be something like this. This code is in the childForm.cs
It works in all cases, swap Form1 for your main form.
Make a Windows Form , then put option for it : CenterParent then use this Code :
Assuming your code is running inside your parent form, then something like this is probably what you're looking for:
For the record, there's also a
Form.CenterToParent()
function, if you need to center it after creation for whatever reason too.If any windows form(child form) is been opened from a new thread of Main window(parent form) then its not possible to hold the sub window to the center of main window hence we need to fix the position of the sub window manually by means of X and Y co-ordinates.
In the properties of Subwindow change the "StartPosition" to be "Manual"
code in main window
code in subwindow for defining its own position by means of parent current position as well as size
Here the co-ordinates of center of parent is calculated as well as the subwindow is kept exactly at the center of the parent by calculating its own center by (this.height/2) and (this.width/2) this function can be further taken for parent relocated events also.
You can set the StartPosition in the constructor of the child form so that all new instances of the form get centered to it's parent:
Of course, you could also set the StartPosition property in the Designer properties for your child form. When you want to display the child form as a modal dialog, just set the window owner in the parameter for the ShowDialog method: