显示另一个与C#生成的表单相邻的表单

如何从Form1生成一个新表单,例如Form2 ,但确保Form2Form1相邻,例如:

在此处输入图像描述

尝试处理主窗体的LocationChanged事件。

简单演示:

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

就像是:

 // button click handler method Form2 child = new Form2(); child.Location = new Point(this.Location.X + this.Width, this.location.Y); child.Show(); 

获取当前表单对象位置的X坐标,并将表单的宽度添加到其中,从而获得新表单的X坐标。 Y坐标保持不变。

 public partial class Form1 : Form { Form2 frm2; public Form1() { InitializeComponent(); frm2 = new Form2(this); frm2.Show(); } } 

和:

 public partial class Form2 : Form { Form1 frm1; public Form2(Form1 frm1) { InitializeComponent(); this.frm1 = frm1; frm1.Move += new EventHandler(Form1_Move); } void Form1_Move(object sender, EventArgs e) { this.Location = new Point(frm1.Location.X + frm1.Width, frm1.Location.Y); } } 

编辑:(由于评论)

要使Form1遵循Form2 ,请添加:

 Move += new EventHandler(Form2_Move); 

Form2的构造函数。

和:

 void Form2_Move(object sender, EventArgs e) { frm1.Location = new Point(Location.X - frm1.Width, Location.Y); } 

在class上。

也许这会对你有所帮助。 Button1在form1上

 private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.StartPosition = FormStartPosition.Manual; form2.SetDesktopLocation(this.Location.X + this.Width, this.Location.Y); form2.ShowDialog(); }