当我在 C# 中移动 Form2 时移动 Form1 [英] Move Form1 when I move Form2 in C#

查看:21
本文介绍了当我在 C# 中移动 Form2 时移动 Form1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种形式.Form2 正在从 Form1 打开,如下所示:

I have two forms. Form2 is being opened from Form1, like this:

Form2.ShowDialog();

Form2

StartPosition配置为centerParent.

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

I need to fix position Form2 in Form1's center, so that when I move Form2, Form1 also changes its location. I have tried many solutions without success.

推荐答案

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

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.

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.

这篇关于当我在 C# 中移动 Form2 时移动 Form1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆