gpt4 book ai didi

c# - 在 C# 中移动 Form2 时移动 Form1

转载 作者:行者123 更新时间:2023-12-02 00:32:43 29 4
gpt4 key购买 nike

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

Form2.ShowDialog();
Form2

StartPosition 配置为 centerParent

我需要将 Form2 的位置固定在 Form1 的中心,以便当我移动 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);
}

此代码不执行任何错误检查,仅是演示代码。

关于c# - 在 C# 中移动 Form2 时移动 Form1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14796367/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com