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

流过昼夜 提交于 2019-12-03 12:32:25

问题


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)

I am unable to understand why these methods exhibit different behavior when working with MDI forms.

I have created an MDIParent and an MDIChild.

I also have a simple winform MyDialogBox that displays its owner on load.

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

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

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.

If so Method A should not work at all, isn't it ?

What am I missing? Why doesn't method B set the owner to MDIChild ?


回答1:


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. However, when calling ShowDialog(IWin32Window), the implementation performs the following call, prior to assigning the value:

owner = ((Control) owner).TopLevelControlInternal;

This might result in assignment of the MDIParent.

(Note: I'm far from being an expert regarding MDI, so I might be wrong here).



来源:https://stackoverflow.com/questions/395186/difference-between-owner-property-and-showdialogiwin32window-owner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!