Max
Max

Reputation: 13388

Open second form, right next first form

I'am using winforms.

I created an application which is nearly finished. Consider the following: I have two forms, the first form starts at application startup, the second form needs to be opened right next to the first form.

Example:

Form collision

How can I access the location of the first form at the second form? Should I send "this" to the constructor of the second form?

EDIT

following code helped me out:

private void changelogToolStripMenuItem_Click(object sender, EventArgs e)
{
     if (_changelog.IsDisposed)
     {
            _changelog = new Changelog();
     }
            _changelog.Location = new Point((Left + Width), Top);
            _changelog.Show();
}

Upvotes: 1

Views: 844

Answers (2)

Skamah One
Skamah One

Reputation: 2456

A basic rule to keep in mind when designing one's constructor: Never give any unnecessary information to the constructor.

So, what you need here is not the other window, but rather it's position. Even better, you need the position where your new window should be located at.

This means that you shouldn't let the second form know about the first form, instead it's constructor should take either:

  1. One parameter Point location
  2. Two parameters int x, int y

Depending on your preferance. You could (should) of course have both constructors, so you can decide whether to give Point location or int x, int y.

This all being said, forget what you read. Better than using a constructor at all, I would just set the property manually when creating the second form:

SecondForm form = new SecondForm()
{
    Location = new Point(this.Right, this.Top)
};

Which is just an other way of saying:

SecondForm form = new SecondForm();
form.Location = new Point(this.Right, this.Top);

Upvotes: 3

Steve
Steve

Reputation: 216363

Why do not position the new form when you open it?

Form2 f = Form2();
f.Location = new Point(this.Left + this.Width, this.Top);
f.Show();  // Or ShowDialog()

Of course, this requires that the second form property StartPosition is set to FormStartPosition.Manual

Upvotes: 1

Related Questions