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

Dan*_* AM 0 c# windows winforms

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

L.E*_*E.O 5

You could create a separate class to manage the form connections and event handling.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Now all you have to do is to instantiate a FormConnector and call ConnectForm method with the form you want to connect to.