gpt4 book ai didi

c# - Form.Owner - 拥有的表单不递归关闭/隐藏

转载 作者:行者123 更新时间:2023-11-30 22:25:37 25 4
gpt4 key购买 nike

MSDN documentation状态:

When a form is owned by another form, it is closed or hidden with the owner form. For example, consider a form named Form2 that is owned by a form named Form1. If Form1 is closed or minimized, Form2 is also closed or hidden.

显然隐藏不是递归工作的?当我有一堆 4 个彼此为父级的表单时(GrandChildForm.Owner = Child; ChildForm.Owner = ParentForm; 等),最小化其中任何一个只会最小化它的直接子级。

关闭这些窗体之一时的类似效果,仅引发直接子级的 FormClosing/Closed 事件,但不会引发其他访问器。 Again the docs不要说这不能递归工作:

If a form has any child or owned forms, a FormClosing event is also raised for each one. If any one of the forms cancels the event, none of the forms are closed.

我要实现的目标:

  • 最小化/恢复表单也应该最小化/恢复它的所有祖先。
  • 关闭表单应该沿着表单层次一直向下到“最小的”子级,如果他们中的任何一个决定不关闭 (FormClosingEventArgs.Cancel = true;) 那么交易是关闭。

这应该使用额外的事件处理来实现(订阅所有者的 FormClosing/FormClosed/SizeChanged 事件)还是我在这里遗漏了什么?

最佳答案

你可以从这个类继承你的表单:

public class AdvancedForm : Form
{
protected override void OnFormClosing(FormClosingEventArgs e)
{
foreach (Form f in this.OwnedForms)
{
f.Close();
}

base.OnFormClosing(e);
}

protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);

foreach (AdvancedForm f in this.OwnedForms)
{
switch (this.WindowState)
{
case FormWindowState.Minimized:
case FormWindowState.Normal:
f.WindowState = this.WindowState;
break;

case FormWindowState.Maximized:
// just restore owned forms to their original sizes when parent form is maximized
f.WindowState = FormWindowState.Normal;
break;
}

// OnSizeChanged must be called, as changing WindowState property
// does not raise SizeChanged event
f.OnSizeChanged(EventArgs.Empty);
}

}
}

或者只在“Closing”和“SizeChanged”事件处理程序中使用此类中的代码。

关于c# - Form.Owner - 拥有的表单不递归关闭/隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12193265/

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