示邻近于彼此形式其从C#衍生形式

2023-09-04 08:27:39 作者:念

如何才有可能产生一个新的形式,例如窗体2 Form1中,但要确保窗体2 为邻 Form1中,例如:

How would it be possible to spawn a new form e.g. Form2 from Form1, but make sure Form2 is adjacent to Form1, for example:

推荐答案

尝试处理主要形式的 LocationChanged 事件。

Try handling the LocationChanged event of the main form.

简单的演示:

public partial class Form1 : Form {
  Form2 f2;

  public Form1() {
    InitializeComponent();
    this.LocationChanged += new EventHandler(Form1_LocationChanged);
  }

  private void button1_Click(object sender, EventArgs e) {
    f2 = new Form2();
    f2.StartPosition = FormStartPosition.Manual;
    f2.Location = new Point(this.Right, this.Top);
    f2.Height = this.Height;
    f2.Show();
  }

  void Form1_LocationChanged(object sender, EventArgs e) {
    if (f2 != null)
      f2.Location = new Point(this.Right, this.Top);
  }
}