sd_dracula
sd_dracula

Reputation: 3896

Winforms Location

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?

Upvotes: 11

Views: 11989

Answers (3)

Hans Passant
Hans Passant

Reputation: 942478

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();

Upvotes: 5

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33391

Location is right property, but you must set

Form.StartPosition = FormStartPosition.Manual;

too.

Upvotes: 5

e_ne
e_ne

Reputation: 8469

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

StartPosition = FormStartPosition.Manual;

Upvotes: 16

Related Questions