且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

同时移动两个表格

更新时间:2023-11-19 14:23:58

假设你有 MainForm 并且在移动它时你想移动所有打开的 ChildForm,你可以使用 LocationChanged 事件处理程序:

Assuming that you have MainForm and when moving it you want to move all opened ChildForms, you can use LocationChanged event handler:

// previous MainForm location
private Point m_PreviousLocation = new Point(int.MinValue, int.MinValue);

private void MainForm_LocationChanged(object sender, EventArgs e) {
  // All open child forms to be moved
  Form[] formsToAdjust = Application
    .OpenForms
    .OfType<ChildForm>()
    .ToArray();

  // If the main form has been moved...
  if (m_PreviousLocation.X != int.MinValue)
    foreach (var form in formsToAdjust) //... we move all child froms aw well
      form.Location = new Point(
        form.Location.X + Location.X - m_PreviousLocation.X,
        form.Location.Y + Location.Y - m_PreviousLocation.Y
      );

  m_PreviousLocation = Location;
}

所以每当 MainForm 移动(改变它的 Location)时,我们也会移动所有的 ChildForm.

so whenever MainForm moves (changes its Location) we move all ChildForms as well.