3

I have a Form that needs to sit on top of two other forms. It should also minimize with one of the two forms it sits above. I found that this works as described when I do

form.Show(null);

However, form.Show() does not work as described. Why? I realize I am passing an owner as the parameter, but the owner is null. So why does the form behave correctly?

2 Answers 2

10

Note that Show() is a method on the Control class and Show(IWin32Window) is a method on the Form class. This is the baked-in behavior of the Show(IWin32Window) method -- if the owner is null, the active window is used as the owner. Control.Show() has no concept of Owner. You can confirm via the MS reference source or a decompiler.

IntPtr hWndActive = UnsafeNativeMethods.GetActiveWindow();
IntPtr hWndOwner = owner == null ? hWndActive : Control.GetSafeHandle(owner); 
4
  • @P.Brian He just means that if you use Show(this) for example, it would show the new window as a child of the current window. Otherwise, when you use Show() which is Show(null), it will be without parent window. A parent window is useful in some cases, such as when you want to prevent user from interacting with parent window while the child window is shown.
    – user586399
    Oct 19, 2012 at 20:50
  • @Desolator - That was my assumption too. Evidently (from the answers) Show() and Show(null) are not calling the same logic at all. Oct 19, 2012 at 20:52
  • @Desolator Show() != Show(null)
    – roken
    Oct 19, 2012 at 20:53
  • @Desolator, actually, Show() is NOT the same as Show(null). Show() is on the Control class, while Show(IWin32Window owner) is on the Form class. Thus the different behaviors.
    – Luc Morin
    Oct 19, 2012 at 20:53
2

When you pass null as the owner window then you force the Show(owner) method overload to go find an owner by itself. It will pick the active window. That's usually the one you want but not always. There are few good reasons to spin that wheel of fortune.

I don't get the "show() doesn't work" part of the question. If you call Show() without argument then the form will not have an owner.

1
  • I'm hooking into a 3rd party application that's running unmanaged code. The window that I want to set as Parent is not available in Application.OpenForms. But...this "active window" trick does work and appears to be able to grab an unmanaged window as the parent. Oct 19, 2012 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.