Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Dialog box at center of its parent

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)
    {
    }
}
like image 847
Tausif Khan Avatar asked Jul 07 '11 06:07

Tausif Khan


4 Answers

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.

like image 76
Kornelije Petak Avatar answered Nov 06 '22 09:11

Kornelije Petak


form1.StartPosition = FormStartPosition.CenterScreen;

See http://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition(v=vs.110).aspx

like image 34
user2070102 Avatar answered Nov 06 '22 09:11

user2070102


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

CenterToParent();

in your custom MessageBox formload() method.

like image 6
Mohsen K Avatar answered Nov 06 '22 11:11

Mohsen K


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();
like image 4
DuyLuc Avatar answered Nov 06 '22 09:11

DuyLuc