Show Dialog box at center of its parent

C#Winforms.Net 4.0PositioningCenter

C# Problem Overview


It's been a mess to show a DialogBox at the center of its parent form. Here is a method to show a dialog.

I am positioning its parent to center but not able to center the DialogBox

private void OpenForm(Object point, Object height, Object width)
{
    FormLoading frm = new FormLoading();
    Point temp = (Point)point;
    Point location = new Point(temp.X + (int)((int)width) / 2, 
                               temp.Y + (int)((int)height) / 2);
    frm.Location = location;
    frm.ShowDialog();
}

private void btnView_Click(object sender, EventArgs e)
{
    try
    {                    
        ThreadStart starter= delegate { OpenForm(currentScreenLocation, 
                                                 this.Height, this.Width); };
        Thread t = new Thread(starter);
        t.Start();
        ////// Some functionality here...
        t.Abort();
    }
    catch (Exception)
    {
    }
}

C# Solutions


Solution 1 - C#

You might want to check the Form.StartPosition property.

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition.aspx

something along the lines of:

private void OpenForm(Form parent)
{
	FormLoading frm = new FormLoading();
    frm.Parent = parent;
	frm.StartPosition = FormStartPosition.CenterParent;
	frm.ShowDialog();
}

This of course requires setting the form's parent.

Solution 2 - C#

Solution 3 - C#

if you are making a custom MessageBox,you can simply put this:

CenterToParent();

in your custom MessageBox formload() method.

Solution 4 - C#

In addition, if you want to set up arbitrary location you can use this

FormLoading frm = new FormLoading();
Point location = new Point(300, 400);
frm.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
frm.Location = location;
frm.ShowDialog();

Solution 5 - C#

NewForm.Show();

NewForm.Top = (this.Top + (this.Height / 2)) - NewForm.Height / 2;
NewForm.Left = (this.Left + (this.Width / 2)) - NewForm.Width / 2;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTausif KhanView Question on Stackoverflow
Solution 1 - C#Kornelije PetakView Answer on Stackoverflow
Solution 2 - C#user2070102View Answer on Stackoverflow
Solution 3 - C#Mohsen KView Answer on Stackoverflow
Solution 4 - C#DuyLucView Answer on Stackoverflow
Solution 5 - C#Billy XdView Answer on Stackoverflow