简体   繁体   English

在C#中移动Form2时移动Form1

[英]Move Form1 when I move Form2 in C#

I have two forms. 我有两种形式。 Form2 is being opened from Form1 , like this: 正在从Form1中打开Form2 ,如下所示:

Form2.ShowDialog();

StartPosition of Form2 is configured to centerParent . Form2 StartPosition配置为centerParent

I need to fix position Form2 in Form1's center, so that when I move Form2 , Form1 also changes its location. 我需要将Form2位置固定在Form1的中心,以便在移动Form2Form1也可以更改其位置。 I have tried many solutions without success. 我尝试了许多解决方案,但均未成功。

You would have to include the parent reference when calling the ShowDialog function, but you would also have to record the initial position difference before using the LocationChanged event. 调用ShowDialog函数时,您必须包括父引用,但是使用LocationChanged事件之前,还必须记录初始位置差。

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

Then in the dialog form, you can wire it up like 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);
}

This code isn't doing any error checking, demonstration code only. 该代码不执行任何错误检查,仅用于演示代码。

Please do beware that this is in general a very undesirable UI feature. 请注意,这通常是非常不受欢迎的UI功能。 Dialogs are annoying because they disable the rest of the windows in the app. 对话框很烦人,因为它们禁用了应用程序中其余的窗口。 Which prevents the user from activating a window to have a look at its content. 这阻止用户激活窗口以查看其内容。 All that the user can do is move a dialog out of the way. 用户所能做的就是将对话框移开。 You are intentionally preventing this from working. 您有意阻止此操作。

Anyhoo, easy enough to implement with the LocationChanged event. Anyhoo,很容易通过LocationChanged事件实现。 Paste this code in the dialog form class: 将此代码粘贴到对话框表单类中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM