如何将两个窗体一起移动?

时间:2010-08-07 06:45:42

标签: c# windows winforms

当我按btn时,我的主要形式是我用showDialog()函数打开新表单, 当我按下主表单时,我需要将两个表单一起移动,因为它们共享 设计。 如何将它们一起移动到主窗体并移动它或者我按下form2然后移动它? 很多任何建议。

2 个答案:

答案 0 :(得分:5)

您可以创建一个单独的类来管理表单连接和事件处理。

class FormConnector
{
    private Form mMainForm;

    private List<Form> mConnectedForms = new List<Form>();

    private Point mMainLocation;

    public FormConnector(Form mainForm)
    {
        this.mMainForm = mainForm;
        this.mMainLocation = new Point(this.mMainForm.Location.X, this.mMainForm.Location.Y);
        this.mMainForm.LocationChanged += new EventHandler(MainForm_LocationChanged);
    }

    public void ConnectForm(Form form)
    {
        if (!this.mConnectedForms.Contains(form))
        {
            this.mConnectedForms.Add(form);
        }
    }

    void MainForm_LocationChanged(object sender, EventArgs e)
    {
        Point relativeChange = new Point(this.mMainForm.Location.X - this.mMainLocation.X, this.mMainForm.Location.Y - this.mMainLocation.Y);
        foreach (Form form in this.mConnectedForms)
        {
            form.Location = new Point(form.Location.X + relativeChange.X, form.Location.Y + relativeChange.Y);
        }

        this.mMainLocation = new Point(this.mMainForm.Location.X, this.mMainForm.Location.Y);
    }
}

现在,您所要做的就是实例化FormConnector并使用您要连接的表单调用ConnectForm方法。

答案 1 :(得分:0)

主要成分是表单“TopLeftLocationWidth属性。假设您有两个表单的引用,称为form1form2。您可以像这样重新定位窗口:

form2.Location = new Point(form1.Left + form1.Width, form1.Top);

结果是两个形式,顶部对齐,右侧是form2。

参考:

http://msdn.microsoft.com/en-us/library/aa984420.aspx