当我在C#中移动Form2时,移动Form1

本文关键字:移动 Form2 Form1 | 更新日期: 2023-09-27 17:58:37

我有两种形式。Form2Form1打开,如下所示:

Form2.ShowDialog();

CCD_ 4的CCD_ 3被配置为CCD_。

我需要将Form2的位置固定在Form1的中心,这样当我移动Form2时,Form1也会改变它的位置。我尝试了许多解决方案,但都没有成功。

当我在C#中移动Form2时,移动Form1

在调用ShowDialog函数时,您必须包括父引用,但在使用LocationChanged事件之前,您还必须记录初始位置差

Form2 f2 = new Form2();
f2.StartPosition = FormStartPosition.CenterParent;
f2.ShowDialog(this);

然后在对话框形式中,您可以将其连接如下:

Point parentOffset = Point.Empty;
bool wasShown = false;
public Form2() {
  InitializeComponent();
}
protected override void OnShown(EventArgs e) {
  parentOffset = new Point(this.Left - this.Owner.Left,
                           this.Top - this.Owner.Top);
  wasShown = true;
  base.OnShown(e);
}
protected override void OnLocationChanged(EventArgs e) {
  if (wasShown) {
    this.Owner.Location = new Point(this.Left - parentOffset.X, 
                                    this.Top - parentOffset.Y);
  }
  base.OnLocationChanged(e);
}

这段代码没有进行任何错误检查,只是演示代码。

请注意,这通常是一个非常不受欢迎的UI功能。对话框很烦人,因为它们会禁用应用程序中的其余窗口。这会阻止用户激活窗口以查看其内容。用户所能做的就是将对话框移开。你故意阻止这种做法。

Anyhoo,很容易通过LocationChanged事件实现。将此代码粘贴到对话框窗体类中:

    private Point oldLocation = new Point(int.MaxValue, 0);
    protected override void OnLocationChanged(EventArgs e) {
        if (oldLocation.X != int.MaxValue && this.Owner != null) {
            this.Owner.Location = new Point(
                this.Owner.Left + this.Left - oldLocation.X,
                this.Owner.Top + this.Top - oldLocation.Y);
        }
        oldLocation = this.Location;
        base.OnLocationChanged(e);
    }