Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms Location

Tags:

c#

winforms

I have an app with 2 forms, the main window and a second Form.

What I want is to open up the second Form on a button click and it's location must be right beside the main form (so if the main form is 600px wide, the X of the new Form will be main.X + 600)

Have tried this but it doesn't seem to take, it opens on top of the main form still:

private void button1_Click(object sender, EventArgs e)
{
    var form = new SecondForm();
    var main = this.Location;
    form.Location = new Point((main.X + 600), main.Y);
    form.Show(); 
}

Is Location not the correct attribute?

like image 856
sd_dracula Avatar asked Jan 12 '13 17:01

sd_dracula


3 Answers

Set your form's StartPosition to FormStartPosition.Manual. You can do it in the designer or from the constructor:

StartPosition = FormStartPosition.Manual;
like image 159
Mir Avatar answered Sep 30 '22 22:09

Mir


Clearly you didn't count on the StartPosition property. Changing it to Manual is however not the correct fix, the second form you load may well rescale itself on another machine with a different video DPI setting. Very common these days. Which in turn can change its Location property.

The proper way is wait for the Load event to fire, rescaling is done by then and the window is not yet visible. Which is the best time to move it in the right place. StartPosition no longer matters now. Like this:

        var frm = new SecondForm();
        frm.Load += delegate {
            frm.Location = new Point(this.Right, this.Top);
        };
        frm.Show();
like image 35
Hans Passant Avatar answered Sep 30 '22 21:09

Hans Passant


Location is right property, but you must set

Form.StartPosition = FormStartPosition.Manual;

too.

like image 22
Hamlet Hakobyan Avatar answered Sep 30 '22 20:09

Hamlet Hakobyan