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?
Set your form's StartPosition
to FormStartPosition.Manual
. You can do it in the designer or from the constructor:
StartPosition = FormStartPosition.Manual;
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();
Location
is right property, but you must set
Form.StartPosition = FormStartPosition.Manual;
too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With