简体   繁体   English

.Owner属性和ShowDialog(IWin32Window所有者)之间的区别?

[英]Difference between .Owner property and ShowDialog(IWin32Window owner)?

I presume a winform's owner can be set explicitly via the .Owner property OR by passing the owner in the overloaded method ShowDialog(IWin32Window owner) 我假设可以通过.Owner属性显式设置winform的所有者,或者通过在重载方法ShowDialog中传递所有者(IWin32Window所有者)

I am unable to understand why these methods exhibit different behavior when working with MDI forms . 我无法理解为什么这些方法在使用MDI表单时表现出不同的行为。

I have created an MDIParent and an MDIChild. 我创建了一个MDIParent和一个MDIChild。

I also have a simple winform MyDialogBox that displays its owner on load. 我还有一个简单的winform MyDialogBox,可以在加载时显示其所有者。

MessageBox.Show("Dialog's owner is " + this.Owner.Name);

Method A - In the load of MDIChild I have the following code, which causes the MyDialogBox's owner to be set to MDIChild 方法A - 在MDIChild的加载中我有以下代码,这导致MyDialogBox的所有者被设置为MDIChild

MyDialogBox box = new MyDialogBox();
box.Owner = this; // Set owner as MDIChild
box.ShowDialog();

Method B - Alternatively, in the load method of MDIChild I have the following code, which causes the MyDialogBox's owner to be set to MDIParent 方法B - 或者,在MDIChild的加载方法中,我有以下代码,它导致MyDialogBox的所有者被设置为MDIParent

MyDialogBox box = new MyDialogBox();
box.ShowDialog(this); // Pass MyMDIChild as owner

I also read the following here 我也在这里阅读以下内容

Only the MDI parent form can own another form, be it a MDI child, a modal dialog or a form where the parent was set as the Owner param. 只有MDI父窗体可以拥有另一个窗体,无论是MDI子窗口,模式对话框还是将父窗口设置为所有者参数的窗体。

If so Method A should not work at all, isn't it ? 如果是这样,方法A根本不起作用,不是吗?

What am I missing? 我错过了什么? Why doesn't method B set the owner to MDIChild ? 为什么方法B没有将所有者设置为MDIChild?

Looking at the differences of these 2 options using Reflector, it seems that they have a slightly different implementation: box.Owner = this just assign the provided value of this to the internal owner field. 使用Reflector查看这两个选项的差异,看起来它们的实现略有不同: box.Owner = this只是将提供的值分配给内部所有者字段。 However, when calling ShowDialog(IWin32Window) , the implementation performs the following call, prior to assigning the value: 但是,在调用ShowDialog(IWin32Window) ,实现会在分配值之前执行以下调用:

owner = ((Control) owner).TopLevelControlInternal;

This might result in assignment of the MDIParent. 这可能导致MDIParent的分配。

( Note : I'm far from being an expert regarding MDI, so I might be wrong here). 注意 :我远不是MDI的专家,所以我可能在这里错了)。

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

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